暑假算法7.23,Day22
字符串
终于到字符串啦,比赛很多字符串的题目,写出来的少之又少,希望可以得到提升吧,加油!!
第一题
class Solution {
public:
string reverseStr(string s, int k) {
int n = s.length();
for (int i = 0; i < n; i += 2 * k) {
reverse(s.begin() + i, s.begin() + min(i + k, n));
}
return s;
}
};
第二题
class Solution {
public:
vector<int> smallestTrimmedNumbers(vector<string>& nums, vector<vector<int>>& queries) {
vector<int> ans(queries.size(),0);
//记录每个字符串的长度为多少
int nSize = nums[0].size();
//循环遍历query
for(int i=0;i<queries.size();i++){
//得到二维数组中每一行的k和trim
int k = queries[i][0];
int trim=queries[i][1];
//存取截取的数,以及其下标
vector<pair<string,int>> t(nums.size());
//遍历nums,存取截取后的字符串以及对应的下标
for(int j=0;j<nums.size();j++){
//String为截取的字符串,int为对应的下标
t[j] = make_pair(nums[j].substr(nSize-trim),j);
}
//对vector<pair<string,int>>类型进行排序,这样即可不丢失下标
//当元素是pair时,vector默认的排序是string比大小
sort(t.begin(),t.end());
ans[i] = t[k-1].second;
}
return ans;
}
};
第三题
class TextEditor {
public:
string left, right;
TextEditor() {
left = "";
right = "";
}
void addText(string text) {
left += text;
}
int deleteText(int k) {
int cnt = 0;
while (!left.empty() && k > 0) {
left.pop_back();
k--;
cnt++;
}
return cnt;
}
string cursorLeft(int k) {
while (!left.empty() && k > 0) {
char ch = left.back();
left.pop_back();
right += ch;
k--;
}
if (left.size() <= 10) {
return left;
}
int pos = left.size() - 10;
return left.substr(pos);
}
string cursorRight(int k) {
while (!right.empty() && k > 0) {
char ch = right.back();
right.pop_back();
left += ch;
k--;
}
if (left.size() <= 10) {
return left;
}
int pos = left.size() - 10;
return left.substr(pos);
}
};
/**
* Your TextEditor object will be instantiated and called as such:
* TextEditor* obj = new TextEditor();
* obj->addText(text);
* int param_2 = obj->deleteText(k);
* string param_3 = obj->cursorLeft(k);
* string param_4 = obj->cursorRight(k);
*/