正序扫描字符串问题
题目
Leetcode Reverse Words in a String
思路
1. 做过几道正序处理字符串的题目, 这些题目的特点是状态比较多, 假如都写在 mian 函数里可能导致思路混乱. 所以总结了一下解决此类题目的框架
2.
void(int) gotoFlow1() {
...
}
void (int) gotoFlow2() {
...
}
int i;
for(i = 0; i < s.size(); i ++) {
if(s[i] == xxxx) { // condition 1
gotoFlow1();
continue;
}
if(i >= s.size())
break;
if(s[i] == uuuu) { // condition 2
gotoFlow2();
continue;
}
}
3. 这个框架外层用 while 函数, 只判断, 不对 i 进行自增操作. 而 gotoFlow 内部则使用 for 循环, 减少代码行数. gotoFlow 函数可以返回值也可以返回 void. 另外, 为了使思路更加顺畅, 最好不要在原始的字符串上操作.
代码一 Reverse Words in a String
#include <iostream>
#include <algorithm>
using namespace std;
string gotoSpace(int &i, const string &s) {
while(i < s.size() && s[i] == ' ')
i ++;
return " ";
}
string gotoWord(int &i, const string &s) {
string cps;
int st = i;
while(i < s.size() && s[i] != ' ') {
i ++;
}
cps = s.substr(st, i-st);
reverse(cps.begin(), cps.end());
return cps;
}
class Solution {
public:
void reverseWords(string &s) {
int i = 0;
while(i < s.size() && s[i] == ' ')
i ++;
s = s.substr(i);
i = s.size() - 1;
while(i >= 0 && s[i] == ' ')
i --;
s = s.substr(0, i+1);
string cps;
i = 0;
while(i < s.size()) {
if(s[i] == ' ') {
cps.append(gotoSpace(i, s));
}
if( i >= s.size())
break;
if(s[i] != ' ') {
cps.append(gotoWord(i, s));
}
}
reverse(cps.begin(), cps.end());
s = cps;
}
};

浙公网安备 33010602011771号