[LeetCode]第八题 :求字符串索引

题目描述:

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

题目解释:

实现strStr()方法。返回needle在haystack中的索引,或者返回-1表示不在haystack中

题目解法:

1.这个其实String早就封装好了indexOf()这个方法就可以求出第二个字符串在第一个字符串中的索引值。当然,出题者肯定想的不是让你用封装的办法写,所以这里还是自己写个实现吧:思路大概就是把String先转成char数组,然后遍历a数组从0到a.length - b.length + 1,然后找是否全部匹配,如果不匹配就继续向后找,匹配则返回索引值i,全部遍历完没有找到则说明没有此子字符串,代码如下:

class Solution {
    public int strStr(String haystack, String needle) {
        char[] a = haystack.toCharArray();
        char[] b = needle.toCharArray();
        if(a.length < b.length) return -1;
        if(a.length == 0 && b.length == 0) return 0;
        if(b.length == 0) return 0;
        for(int i = 0; i < a.length - b.length + 1;i++) {
            if(a[i] == b[0]) {
                boolean flag = true;
                for(int j = 0; j < b.length;j++) {
                    if(a[i + j] != b[j]) {
                        flag = false;
                        break;
                    }
                }
                if(flag) return i;
            }
        }
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80806024