题目:
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
分析:
这道题的原理和剑指Offer-43.左旋转字符串(C++/Java)类似,先将字符串整体翻转一次,然后根据空格划分单词,将每个单词翻转一次即可得到答案。
程序:
C++
class Solution { public: string ReverseSentence(string str) { myReverse(str, 0, str.size()-1); int index = 0; int l = 0; while(index < str.size()){ if(str[index] == ' '){ myReverse(str, l, index-1); l = index + 1; } else if(index == str.size()-1){ myReverse(str, l, index); break; } index++; } return str; } void myReverse(string &str, int l, int r){ if(l > str.size()-1 || r < 0) return; while(l < r){ swap(str[l], str[r]); l++; r--; } } };
Java
public class Solution { public String ReverseSentence(String str) { StringBuilder s = new StringBuilder(str); myReverse(s, 0, s.length()-1); int l = 0; int r = 0; while(r < s.length()) { if(s.charAt(r) == ' '){ myReverse(s, l, r-1); l = r + 1; } else if(r == s.length()-1){ myReverse(s, l, r); break; } r++; } return s.toString(); } public static void myReverse(StringBuilder str, int l, int r) { if(r < 0 || l > str.length()-1) return; while(l < r) { swap(str, l, r); l++; r--; } } public static void swap(StringBuilder str, int l, int r) { char temp = str.charAt(l); str.setCharAt(l, str.charAt(r)); str.setCharAt(r, temp); } }