/*翻转字符串*/
/* “I am a student.”变为“student. a am I”。*/
class Solution {
public:
string ReverseSentence(string str) {
if (str.empty()) return str;
reverse(str.begin(), str.end());
string::iterator pBegin = str.begin();
string::iterator pEnd = str.begin();
string::iterator End = str.end();
while (pBegin!=End)
{
if (*pBegin == ' ')
{
pBegin++;
pEnd++;
}
else if (*pEnd == ' ' || pEnd ==End)
{
reverse(pBegin, pEnd);
pBegin = pEnd;
}
else
pEnd++;
}
return str;
}
};
/*左旋转字符串*/
/*对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。
例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,
即“XYZdefabc”。*/
class Solution {
public:
string LeftRotateString(string str, int n) {
if (!str.empty()&& n>0 && n<str.size())
{
reverse(str.begin(), str.begin() + n);
reverse(str.begin() + n, str.end());
reverse(str.begin(), str.end());
}
return str;
}
};