/** * 题目: * 牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。 * 同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。 * 后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。 * Cat对一一的翻转这些单词顺序可不在行,你能帮助他么? * * 解题思路: * 先翻转整个句子,然后再翻转句中的单词。 */ public class P284_ReverseSentence { public String ReverseSentence(String str){ String result = ""; if (str == null) { return result; } int start = 0; int end = str.length() - 1; String temp = ReverseWords(str,start,end); char[] array = temp.toCharArray(); for (int i = 0; i < array.length; i++) { int low = i; while (i < array.length && array[i] != ' ') { i++; } int high = i - 1; temp = ReverseWords(temp, low, high); } result = temp; return result; } public String ReverseWords(String str, int start, int end) { char[] array = str.toCharArray(); while (start < end) { char temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end--; } String result = new String(array); return result; } public static void main(String[] args) { String str = "I am a student."; P284_ReverseSentence test = new P284_ReverseSentence(); String result = test.ReverseSentence(str); System.out.println(result); } }
剑指offer:翻转单词顺序(java)
猜你喜欢
转载自blog.csdn.net/Sunshine_liang1/article/details/82877613
今日推荐
周排行