题目一:输入一个英文句子,翻转句子中的单词的顺序,但单词内的字符顺序不变,为了简单起见,标点符号作为字母处理。如:
"I am a student!" 翻转为 "student! a am I"
分析:可以截取每个词然后拼接,但是很麻烦。观察单词的规律可以看出,可以先翻转每个单词,然后在对整个字符串进行翻转就可以得到结果;或者先翻转,后逐个翻转。
class Solution {
public:
string ReverseSentence(string str) {
string res(str);
if (!str.empty()) {
reverse(res, 0, res.size() - 1);
int low = 0;
for (int high = 0; high <= res.size(); ++high)
{
if (res[high] == ' ' || high == res.size())
{
reverse(res, low, high - 1);
low = high + 1;
}
}
}
return res;
}
//就地逆置string
void reverse(string &str, int low, int high)
{
while(low < high){
char c = str[low];
str[low] = str[high];
str[high] = c;
++low, --high;
}
}
};
题目二:字符串的左旋转操作是把字符串前面的若干字符串转移到字符串尾部。如“abcdefg”和数字2, 输出“cdefgab”。直接进行移动规律比较难把控,如果不用辅助空间的话,我试试:
解法一:硬着头皮找规律不能用辅助空间
算了,不求了。
解法二:分别对前后两部分逆置,然后整体逆置即为所求结果
class Solution {
public:
string LeftRotateString(string str, int n) {
string res = "";
if(!str.empty() && n >= 0)
{
n = n % str.size();
Reverse(str, 0, n-1);
Reverse(str, n, str.size() - 1);
Reverse(str, 0, str.size()-1);
res = str;
}
return res;
}
void Reverse(string &str, int low, int high)
{
while(low < high)
{
char c = str[low];
str[low] = str[high];
str[high] = c;
++low;
--high;
}
}
};