/*
問題描述:給定一個字符串,單詞以空格隔開,對字符串進行轉換,例如“I love you”轉換成“you love I”,要求空間複雜度爲O(1)
來源:網易算法課
日期:2017-10-24
說明:共分爲兩步,第一步:將整個字符串進行翻轉;第二步:對每個單詞進行翻轉
*/
#include <iostream>
#include <string>
using namespace std;
void reverseString(string& str, int begin, int end)
{
int i = begin, j = end;
while (i < j)
{
char c = str[i];
str[i] = str[j];
str[j] = c;
i++;
j--;
}
//cout << str << endl;
}
void reverseWord(string& str)
{
reverseString(str, 0, str.length() - 1);
cout << str << endl;
int begin = 0, end = begin;
while (end < str.length())
{
while (str[end] != ' ' && end < str.length())
end++;
reverseString(str, begin, end - 1);
begin = end + 1;
end = begin;
}
}
/*
int main()
{
string str = "im love you";
//reverseString(str, 0, str.length() - 1);
reverseWord(str);
cout << str << endl;
return 0;
}
*/
字符串中旋轉單詞
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.