LeetCode28. Implement strStr()

題目

Implement strStr().

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


思路

就是一個找子串的函數。

先順勢掃描,尋找首字母的匹配項,之後利用subString函數看剩餘串是否匹配,如果匹配則最終返回i;尋找下一個首字母匹配位置;直到循環結束。


代碼

public class Solution {
    public int strStr(String haystack, String needle) {
        if(needle.length() == 0 && haystack.length() == 0)  return 0;
        if(haystack.length() == 0 || haystack.length() < needle.length())  return -1;
        if(needle.length() == 0)    return 0;
        int strStr = -1;
        int length = needle.length();
        char firstOfNeedle = needle.charAt(0);
        for(int i = 0; i < (haystack.length() - length + 1) ; ++ i){
            if(firstOfNeedle == haystack.charAt(i)){
                if(haystack.substring(i , i + length).equals(needle))   return i;
            }
        }
        return strStr;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章