反转字符串中的单词
class Solution {
public:
string reverseWords(string s)
{
int slow = 0;
int i = 0;
while(i < s.size())
{
if(s[i] != ' ')
{
if(slow != 0)
{
s[slow++] = ' ';
}
while(i < s.size() && s[i] != ' ')
{
s[slow++] = s[i++];
}
}
else
{
++i;
}
}
s.resize(slow);
reverse(s.begin(), s.end());
i = 0;
int j = 0;
while(j < s.size())
{
if(s[j] == ' ')
{
reverse(s.begin() + i, s.begin() + j);
j++;
i = j;
}
else
{
++j;
}
}
reverse(s.begin() + i, s.begin() + j);
return s;
}
};
右旋字符串
include
include
using namespace std;
class Solution
{
public:
void rotateStr(string s, int k)
{
int i = 0;
int j = 0;
for(int a = 0; a < k; ++a)
{
++j;
}
while(j < s.size())
{
++i;
++j;
}
string str1 = s.substr(i, j);
string str2 = s.substr(0, i);
cout << str1 << str2 << endl;
}
};
int main()
{
int k = 0;
cin >> k;
string s;
cin >> s;
Solution solution;
solution.rotateStr(s, k);
return 0;
}