28. Implement strStr()
代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
int offset;
int h = haystack.length();
int n = needle.length();
int i;
if(n==0)
return 0;
if(h==0)
return -1;
for(i = 0; i< h-n+1; i++){
for(offset = 0; offset < n; ){
if(haystack[i+offset]==needle[offset])
offset++;
else
break;
}
if(offset == n)
return i;
}
if(offset == n)
return i;
else
return -1;
}
};
还可以用flag;
还可以用KMP, 以后有时间再尝试;
//for(offset = 0; offset < n; ){
曾出错;
38. count and say
第一次尝试递归,有时间尝试一下非递归。
代码如下:
string countAndSay(int n) {
if(n == 1)
return "1";
if(n == 2)
return "11";
string res = "";
//int i;
string res_tmp = countAndSay(n-1);
int count = 1;
int length = res_tmp.length();
for(int i = 1; i < length ; i++){
if(res_tmp[i] == res_tmp[i-1]){
count++;
}
else{
res.push_back('0'+count);
res.push_back(res_tmp[i-1]);
count = 1;
}
if(i == length-1){
res.push_back('0'+count);
res.push_back(res_tmp[i]);
}
}
return res;
}