Reverse the word in a sentence. Like: input ”Hello world Amazon”, output “olleH dlrow nozamA”
#include <string>
#include <iostream>
#include <cstdio>
using namespace std;
class Solution
{
public:
static void reverse_word(std::string& sentence, int start, int end)
{
int length = end - start;
for (int i = start; i < (start + length / 2); i++)
{
char before = sentence[i];
end--;
sentence[i] = sentence[end];
sentence[end] = before;
}
}
static void reverse_sentence(std::string& sentence)
{
if (sentence.length() <= 1)
return;
int length = sentence.length();
for (int start = 0, end = 0; start < length && end <= length; end++)
{
if (end == length || sentence[end] == ' ')
{
reverse_word(sentence, start, end);
start = end + 1;
}
}
}
};
int main(int argc, char * * argv, char * * env)
{
std::string sentence = "Hello world Amazon";
Solution::reverse_sentence(sentence);
std::cout << sentence << std::endl;
char ch;
scanf_s("%c", &ch);
return 0;
}
总结:
1. 写的过程中没有考虑末尾单词无空格,被interviewee指出来了,当场修正了;
2. 代码写的时候用的是sentense,不是代码中的sentence,单词拼写错误,面试结束才发现这个问题;
3. reverse_word函数很明显可以采用双端指针写的可读性更好,但是写的过程中还是略微紧张,写成了上面的代码,被interviewee质疑了下,但是解释之后才发现没有错误。
(PS. main test stub是后加的,代码逻辑没有问题)
bless!!!