旋转字符串:
Reverse Words in a String:
算法: 先是整体旋转,啊然后是旋转个体。 “the sky is blue”,
“blue is sky the”.
细节部分
1. 对于空格怎么处理,然后就是 像这样的字符串处理“1 ”;
用一个Count计数,当count >= 1 , 判断后面是否有汉子,有的 + ‘ ’;
否则直接退出
代码:
class Solution {
public:
void reverseWords(string &s) {
int n = s.size();
if(n == 0)
{
s = "";
return;
}
int i=0,j=n-1;
while(i < j)
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
i=0,j=0;
int l=0,Count=0; //Count 计算后面是否需要加“ ”;
while(i < n)
{
while(i < n && s[i] == ' ')
{
i++;
}
if(i == n) //判断后面是有单词
{
break;
}
if(Count)
{
s[j] = ' '; //前面有的话, 就+‘ ’;
j++;
}
l = j;
while(i < n && s[i] != ' ')
{
s[j] = s[i];
i++;
j++;
}
int d1 = l, d2 = j-1;
while(d1 < d2)
{
char temp = s[d1];
s[d1] = s[d2];
s[d2] = temp;
d1++;
d2--;
}
Count++;
}
s.resize(j);
}
};