首页 > 编程语言 > 代码随想录算法训练营第八天 | 反转字符串、反转字符串II,剑指Offer 05.替换空格,左旋转字符串,翻转字符串里的单词

代码随想录算法训练营第八天 | 反转字符串、反转字符串II,剑指Offer 05.替换空格,左旋转字符串,翻转字符串里的单词

时间:2023-01-18 19:45:12浏览次数:82  
标签:begin right string int 反转 随想录 字符串 left

344.反转字符串

class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = s.size() - 1;
while (left < right) {
swap(s[left],s[right]);
left++;
right--;
}
}
};

541. 反转字符串II

class Solution {
public:
void reverse(string &s,int left,int right) {
while (left < right) {
swap(s[left],s[right]);
left++;
right--;
}
}
string reverseStr(string s, int k) {
int left = 0,right = 0;
int num = 0;
int begin = 0;
for (int i = 0; i < s.size(); ++i) {
num++;
if (num == 2*k) {
left = begin;
right = i - k;
reverse(s,left,right);
begin = i + 1;
num = 0;
}
}
if(num < k) {
left = begin;
right = s.size() - 1;
reverse(s,left,right);
}
if (num >= k && num < 2 * k) {
left = begin;
right = begin + k - 1;
reverse(s,left,right);
}
return s;
}
};

剑指Offer 05.替换空格

class Solution {
public:
string replaceSpace(string s) {
string result;
for (int i = 0; i < s.size();++i) {
if (s[i] == ' ') result += "%20";
else {
result += s[i];
}
}
return result;
}
};

剑指Offer58-II.左旋转字符串

class Solution {
public:
string reverseLeftWords(string s, int n) {
string reStr = s.substr(0,n);
string result = s.substr(n,s.size()-1);
return result + reStr;
}
};

class Solution {
public:
string reverseLeftWords(string s, int n) {
reverse(s.begin(),s.begin()+n);
reverse(s.begin()+n,s.end());
reverse(s.begin(),s.end());
return s;
}
};

151.翻转字符串里的单词

class Solution {
public:
void removeSpace(string& s) {
int slow = 0, fast = 0;
for (; fast < s.size(); ++fast) {
if (s[fast] != ' ') {
if (slow != 0) s[slow++] = ' ';
while (slow <= fast && fast < s.size() && s[fast] != ' ') {
s[slow] = s[fast];
slow++;
fast++;
}
}
}
s.resize(slow);
}


string reverseWords(string s) {
removeSpace(s);
reverse(s.begin(), s.end());
int begin = 0;
for (int i = 0; i <= s.size(); ++i) {
if (s[i] == ' ' || i == s.size()) {
reverse(s.begin() + begin, s.begin() + i);
begin = i + 1;
}
}
return s;
}
};

标签:begin,right,string,int,反转,随想录,字符串,left
From: https://www.cnblogs.com/masene/p/17060452.html

相关文章