leetcode28_C++實現strStr()函數


實現 strStr() 函數。

給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回  -1。

示例 1:

輸入: haystack = "hello", needle = "ll"
輸出: 2

示例 2:

輸入: haystack = "aaaaa", needle = "bba"
輸出: -1

說明:

當 needle 是空字符串時,我們應當返回什么值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。


 

思路:以haystack="mississippi" ,needle="issip"為例子..

1.判斷needle長度是否小於haystack

2.判斷2個字符串為空的情況

3.判斷正常情況

  a.如果haystack(i)==needle(j),則j++。若不相同,則i需要回到之前判斷的數的后一位,也就是+1。

  如:

      i:        0   1    2    3   4   5  6   7  8   9   10(數組下標)

haystack :      m   i    s    s    i   s   s   i   p    p   i

needle    :             i    s    s    i   p    

haystack(5)與needle(5)不相同,則又要重新循環,既,haystack(2)開始循環。

      i:       0  1    2    3   4   5  6   7  8   9   10(數組下標)

haystack :      m   i    s    s   i   s   s   i   p    p   i

needle    :                  i     s   s   i    p    

 

     .............以此類推

 

      i:       0  1    2    3   4   5  6   7  8   9   10(數組下標)

haystack :      m   i    s    s   i   s   s   i   p    p   i

needle    :                             i   s   s    i   p    

 

如果, j的長度與needle相同,則返回 i-needle的長度。

 

 

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.size()==0)
            return 0;
        if (needle.size() > haystack.size())
            return -1;
        int j=0;//用來指向needle的字符串
        int i=0;
        for (i = 0; i < haystack.size(); i++) {
            if (j==needle.size()){//如果已經匹配完成則返回
                return i - needle.size();
            }
            if (haystack[i] == needle[j]){
                j++;
            } else{
                i -= j;
                j=0;
            }
        }
        //用來判斷單個字母的時候,j++之后j=1,i=1;
        if (j==needle.size()){
            return i - needle.size();
        }
        return -1;
    }
};

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM