代码随想录day09 151.翻转字符串里的单词 、卡码网:55.右旋转字符串
151. 反转字符串中的单词
这题我直接想到的是istringstream 和 stack 但不知道这样使用是不是违反了规定
class Solution {
public:
string reverseWords(string s) {
istringstream iss(s);
string word;
stack<string> st;
string res;
while (iss >> word) {
st.push(word);
}
while (!st.empty()) {
res += st.top();
st.pop();
if (!st.empty()) {
res += " ";
}
}
return res;
}
};
看了卡哥的O(1)空间复杂度解法,写了下述代码
class Solution {
public:
void removeSpaces(string &s) {
int left = 0;
int right = 0;
int len = s.size();
while (right < len) {
if (s[right] != ' ') {
if (left != 0) {
s[left++] = ' ';
}
while (right < len && s[right] != ' ') {
s[left++] = s[right++];
}
} else {
right++;
}
}
s.resize(left);
}
string reverseWords(string s) {
removeSpaces(s);
reverse(s.begin(), s.end());
int left = 0;
int right = 0;
int len = s.size();
while (right < len) {
while (right < len && s[right] != ' ') {
right++;
}
reverse(s.begin() + left, s.begin() + right);
left = ++right;
}
return s;
}
};
卡码网:55.右旋转字符串
方法很巧妙
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int n;
string s;
cin >> n;
cin >> s;
int len = s.size(); //获取长度
reverse(s.begin(), s.begin() + len - n);
reverse(s.begin() + len - n, s.end());
reverse(s.begin(), s.end());
cout << s << endl;
}