字符串原地修改经常遇到的一类题,双指针一个用于写入,一个用于扫描,互不干扰,各司其职。
题目:https://leetcode.cn/problems/reverse-words-in-a-string/
string reverseWords(string s) {
reverse(s.begin(), s.end());
int write = 0, scan = 0;
while (scan <= s.size()) {
if (scan == s.size() || s[scan] == ' ') {
// 屏蔽开头是空格情况
if (write == 0) {
scan++;
continue;
}
// 反转单词
int w = write - 1;
while (w >= 0 && s[w] != ' ') w--;
reverse(s.begin() + w + 1, s.begin() + write);
// scan后面没有有效单词退出
while (scan < s.size() && s[scan] == ' ') scan++;
if (scan == s.size()) break;
// 单词之间补充空格
s[write++] = ' ';
} else {
s[write++] = s[scan++];
}
}
return s.substr(0, write);
}
题目:https://leetcode.cn/problems/string-compression/
int compress(vector<char>& chars) {
int write = 0, i = 0;
while (i < chars.size()) {
if (i + 1 < chars.size() && chars[i] == chars[i + 1]) {
chars[write++] = chars[i++];
int count = 2;
while (i + 1 < chars.size() && chars[i] == chars[i + 1]) {
i++;
count++;
}
i++;
stack<char> s;
while (count) {
s.push('0' + count % 10);
count /= 10;
}
while (!s.empty()) {
chars[write++] = s.top();
s.pop();
}
} else {
chars[write++] = chars[i++];
}
}
return write;
}
题目:https://leetcode.cn/problems/removing-stars-from-a-string/
string removeStars(string s) {
int write = 0, scan = 0;
while (scan < s.size()) {
if (s[scan] == '*') {
write--;
scan++;
continue;
}
s[write++] = s[scan++];
}
return s.substr(0, write);
}
标签:string,scan,++,chars,原地,write,while,字符串,指针
From: https://www.cnblogs.com/linukey/p/17430599.html