读入带空格的string串
string str;
getline(cin, str);
实现 strStr()
#include <bits/stdc++.h>
#include <string>
#include <string.h>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle == "") {
return 0;
}
int len = haystack.size();
int ans = haystack.find(needle);
if(ans < len) return ans;
else return -1;
}
};
外观数列
1.不知道如何保存上一次的数列,然后用于下一次来遍历。
2.记得遍历的count是整形变量,加入string 要先to_string();
3.string类型加长度直接 string ans; ans = ans + "Something u wanna add";
4.此题一定要注意细节就是 在for循环中,每次用ans赋值给新的temp时,ans都要至于重新初始化!我忽略了这一点!
class Solution {
public:
string countAndSay(int n) {
if(n == 1) return "1";
else if(n == 2) return "11";
string temp = "11";
string ans = "";
n -= 2;
for(int k = 0; k < n; ++k){
int count = 1;
for(int i = 0; i < temp.size(); ++i) {
if(temp[i] == temp[i + 1]) {
count++;
}
else {
ans = ans + to_string(count) + temp[i];
count = 1;
}
}
temp = ans;
ans = "";
}
return temp;
}
};
最长公共前缀
1.二维vector数组str,str.size()表示行,str[0].size()表示列的长度。
2.此题是找前缀哦!
/**
@author: ZhengXiaoTao
@description:
*/
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 1) {
return strs[0];
}
string ans = "";
for(int i = 1; i < strs.size(); ++i) {
int len = max(strs[i].size(), strs[i - 1].size());
string temp = "";
for(int j = 0; j < len; ++j) {
if(strs[i][j] == strs[i - 1][j]) {
temp += strs[i - 1][j];
}
else {
break;
}
}
strs[i] = temp;
ans = temp;
}
return ans;
}
};