以下為個人解題思路,不一定是最好的解法,但應該還是有用~
子字串
沒錯這題就是在考子字串,c++ 和 python 都有現成的函式,當然也可以自己刻一個當然練習~
程式碼 - 現成函式
- c++
- python
// use c++
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};
程式碼 - 自己刻
// use c++
class Solution {
public:
int strStr(string haystack, string needle) {
int hay_len=haystack.size();
int needle_len=needle.size();
int j,k;
// haystack 每個 index 都去比較,看會不會和 needle 一樣
for(int i=0; i<hay_len; i++){
j=i;
k=0;
for(; k<needle_len; k++, j++){
if(haystack[j] != needle[k]){
break;
}
}
if(k == needle_len){
return i;
}
}
return -1;
}
};
0 Comments
張貼留言