今日LeetCode--28,38
2017-05-15 15:03
411 查看
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;
}
代码如下:
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;
}
相关文章推荐
- LeetCode (28)Implement strStr()
- [LeetCode28]Divide Two Integers
- LeetCode 38 - Count and Say
- leetcode-38 Count and Say
- leetcode28 完成strstr
- Leetcode 38 Count and Say
- LeetCode 38 -- Count and Say
- [LeetCode 38] Count and Say
- leetcode 28 Implement strStr()
- 【LeetCode】38 - Count and Say
- leetCode(28):Contains Duplicate II
- Leetcode 38 Count and Say
- leetcode 38 Count and Say C++
- [C++]LeetCode: 28 Valid Sudoku
- Leetcode 28 Implement strStr()
- leetcode-38 Count And Say
- leetcode28
- leetcode 28
- LeetCode 38 Count and Say
- leetcode38 Count and Say