Implement strStr()

来源:互联网 发布:淘宝男士内衣 编辑:程序博客网 时间:2024/04/30 16:42

题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

思路:

直接暴力掉了。。

public class Solution {    public int strStr(String haystack, String needle) {        if (haystack == null || needle == null ||                (haystack.length() == 0 && needle.length() != 0)) {            return -1;        }        if ((haystack.length() == 0 && needle.length() == 0) ||                 (haystack.length() != 0 && needle.length() == 0)) {            return 0;        }        for (int i = 0;i < haystack.length()-needle.length()+1;i++) {            if (haystack.charAt(i) == needle.charAt(0)) {                int j;                for (j = 1;j < needle.length();j++) {                    if (haystack.charAt(i+j) != needle.charAt(j)) {                        break;                    }                }                if (j == needle.length()) {                    return i;                }            }        }        return -1;    }}


0 0
原创粉丝点击