方法:模拟
class Solution {
public:
void reverseString(vector<char>& s) {
int n = s.size(), len = n / 2;
for (int i = 0; i < len; ++i) {
swap(s[i], s[n-i-1]);
}
}
};
$时间复杂度O(n), 空间复杂度O(1);
方法:双指针
class Solution {
public:
string reverseStr(string s, int k) {
int n = s.size(), start = 0, end;
int i, j;
for (i = 0; start < n; i += 2*k) {
end = start + 2 * k;
if (end > n) end = n;
if (end - start >= k && end - start <= 2 * k) {
for (j = start; j < start + k / 2; ++j) swap(s[j], s[2*start+k-j-1]);
} else {
for (j = start; j < start + (end-start)/2; ++j) swap(s[j], s[end-j-1+start]);
}
start = end;
}
return s;
}
};
$时间复杂度O(n*k), 空间复杂度O(1);
方法:模拟
class Solution {
public:
string replaceSpace(string s) {
string str;
for (char& c : s) {
if (c == ' ') {
str += "%20";
} else str += c;
}
return str;
}
};
$时间复杂度O(n), 空间复杂度O(1);
方法:模拟
class Solution {
private:
void removeExtraspace(string& s) {
int slow = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] != ' ') {
if (slow != 0) s[slow++] = ' ';
while (s[i] != ' ' && i < s.size()) s[slow++] = s[i++];
}
}
s.resize(slow);
}
public:
string reverseWords(string s) {
removeExtraspace(s);
reverse(s.begin(), s.end());
for (int i = 0, st = 0; i <= s.size(); ++i) {
if (s[i] == ' ' || i == s.size()) {
reverse(s.begin() + st, s.begin() + i);
st = i + 1;
}
}
return s;
}
};
$时间复杂度O(), 空间复杂度O(n);
方法:模拟
class Solution {
public:
string reverseLeftWords(string s, int k) {
reverse(s.begin(), s.begin()+k);
reverse(s.begin()+k, s.end());
reverse(s.begin(), s.end());
return s;
}
};
$时间复杂度O(n), 空间复杂度O(1);