Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
1 class Solution { 2 public: 3 int strStr(string haystack, string needle) { 4 //這個題不難,關鍵是條件有很多,要判斷對 5 //a 0 0 6 //0 0 0 7 //0 a -1 8 //haystack長度 needle長度 返回值 9 //如果needle比haystack長,返回-1 10 if(needle.size() == 0) 11 return 0; 12 13 if(haystack.size() == 0 && needle.size() != 0) 14 return -1; 15 16 if(haystack.size() < needle.size()) 17 return -1; 18 19 for(int i = 0; i < haystack.size() - needle.size() + 1; i++){ 20 21 int j = 0; 22 for(j; j < needle.size(); j++){ 23 if(haystack[i+j] != needle[j]) 24 break; 25 } 26 if(j == needle.size()) 27 return i; 28 } 29 return -1; 30 31 } 32 };