纯刷题,几个关于string的题
一般string的题就是顾名思义,把human的想法code出来,算法要求低一些
常用API:
cur += to_string(count) + res[i];
int len = stoi(s.substr(start, curpos - start));
int curpos = s.find_first_of(’/’, start);
- Count and Say
1. 1
2. 11
3. 21
4. 1211
5. 111221
class Solution {
public:
string countAndSay(int n) {
if(n < 1) return "zero";
string res="1";
while(--n)
{
string cur = "";
for(int i = 0; i < res.size(); i++)
{
int count = 1;
while((i+1) < res.size() && res[i] == res[i+1])
{
count ++;
i ++;
}
cur += to_string(count) + res[i];
}
res = cur;
}
return res;
}
};
- Encode and Decode Strings
the easy confusing part is:what if the original string is “2”?
well,
the encoder returns: “2\2”
the decoder:
1, find the first of
2, get length 2;
3, return “2”
so no worries.
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string res = "";
for(auto str : strs)
{
res += to_string(str.size()) + "/" + str;
}
return res;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string>res;
int start = 0;
while(start < s.size())
{
int curpos = s.find_first_of('/', start);
int len = stoi(s.substr(start, curpos - start));
start = curpos + 1;
res.push_back(s.substr(start, len));
start += len;
}
return res;
}
};
- String Compression
Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
class Solution {
public:
int compress(vector<char>& chars) {
int oldindex = 0;
int newindex = 0;
while(oldindex < chars.size())
{
//save the char
char curchar = chars[oldindex];
//count the repeat
int count = 0;
while(oldindex < chars.size() && chars[oldindex] == curchar)
{
oldindex++;
count++;
}
//build the new str
chars[newindex++] = curchar;
//add the count to the new str
if(count != 1)
{
string countstr = to_string(count);
for(auto c : countstr)
{
chars[newindex++] = c;
}
}
}
return newindex;
}
};