题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
在这里有两种处理方法:
一种是利用栈先进后出性质,倒装句子,而不需要翻转单词;
一种是全部翻转整个字符串,然后再单独翻转单词。
string ReverseSentenceFirst(string str) {//第一种方法
stack<string> rever;
int start = 0, end = 0;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == ' ')
rever.push(" ");
if (str[i] == ' ' && str[i + 1] != ' ')
start = i + 1;
if (str[i] != ' ' && (str[i + 1] == ' ' || i == str.length() - 1))
end = i + 1;
if (end>start)
{
string tmp;
tmp.resize(end - start + 1);//多分配一个空间,防止单个非空格字符在重组字符串的时候当作空格处理
int count = 0;
for (int j = start; j < end; j++)
tmp[count++] = str[j];
rever.push(tmp);
end = start = 0;
}
}
stack<string> rever;
int start = 0, end = 0;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == ' ')
rever.push(" ");
if (str[i] == ' ' && str[i + 1] != ' ')
start = i + 1;
if (str[i] != ' ' && (str[i + 1] == ' ' || i == str.length() - 1))
end = i + 1;
if (end>start)
{
string tmp;
tmp.resize(end - start + 1);//多分配一个空间,防止单个非空格字符在重组字符串的时候当作空格处理
int count = 0;
for (int j = start; j < end; j++)
tmp[count++] = str[j];
rever.push(tmp);
end = start = 0;
}
}
string restr;
string restr1;
restr1.resize(str.length());
int count = 0;
string restr1;
restr1.resize(str.length());
int count = 0;
while (!rever.empty())
{
string tmp = rever.top();
cout << "tmp:" << tmp << tmp.length() - 1<<endl;
if (tmp.length() - 1 == 0)
{
restr1[count] = ' ';
count++;
}
for (int i = 0; i < tmp.length() - 1; i++)
{
restr1[count] = tmp[i];
count++;
}
rever.pop();
}
return restr1;
}
{
string tmp = rever.top();
cout << "tmp:" << tmp << tmp.length() - 1<<endl;
if (tmp.length() - 1 == 0)
{
restr1[count] = ' ';
count++;
}
for (int i = 0; i < tmp.length() - 1; i++)
{
restr1[count] = tmp[i];
count++;
}
rever.pop();
}
return restr1;
}
string ReverseSentenceSecond(string str)//第二种方法
{
//第一步,全盘翻转
int i = 0, j = 0;
j = str.length()-1;
char tmp;
while (j>i)
{
tmp = str[j];
str[j] = str[i];
str[i] = tmp;
j--;
i++;
}
{
//第一步,全盘翻转
int i = 0, j = 0;
j = str.length()-1;
char tmp;
while (j>i)
{
tmp = str[j];
str[j] = str[i];
str[i] = tmp;
j--;
i++;
}
//第二步,翻转单词
i = 0;
int start = 0, end = 0;
while (str[i])
{
if (str[i] != ' ')//得到单词的开始位置和结束位置
{
start = i;
while (str[i] && str[i] != ' ')
i++;
i = i - 1;
end = i;
}
i = 0;
int start = 0, end = 0;
while (str[i])
{
if (str[i] != ' ')//得到单词的开始位置和结束位置
{
start = i;
while (str[i] && str[i] != ' ')
i++;
i = i - 1;
end = i;
}
while (start < end)//翻转单词
{
tmp = str[start];
str[start] = str[end];
str[end] = tmp;
end--;
start++;
}
{
tmp = str[start];
str[start] = str[end];
str[end] = tmp;
end--;
start++;
}
i++;
}
}
return str;
}