微软算法100题10 翻转句子中单词的顺序

第10 题
翻转句子中单词的顺序。
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例如输入“I am a student.”,则输出“student. a am I”

 

思路:可以先翻转整个字符串,然后依次截取各个单词,在对单词进行翻转,目前的解决方案默认每个单词之间只有一个空格,可以考虑如果有多个空格的情况

 

 1 package com.rui.microsoft;
 2 /**
 3  * 翻转句子中单词的顺序。
 4 题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
 5 句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
 6 例如输入“I am a student.”,则输出“student. a am I”
 7  */
 8 public class Test10_ReverseStringInSentence {
 9 
10     public static void main(String[] args) {
11         String s = "I AM A STUDENT";
12         char[] ss = s.toCharArray();
13         reverse(ss, 0, ss.length - 1);
14         reverseAll(ss);
15         System.out.println(String.copyValueOf(ss));
16     }
17     
18     public static void reverse(char[] s, int start, int end){
19         while(start < end){
20             char temp = s[start];
21             s[start] = s[end];
22             s[end] = temp;
23             start++;
24             end--;
25         }
26     }
27     
28     public static void reverseAll(char[] sentence){
29         int i = 0, start = 0;
30         while(i < sentence.length){
31             if(sentence[i] != ' '){
32                 i++;
33             }else{
34                 reverse(sentence, start, i-1);
35                 //move pointer 'start' to the character after pointer i
36                 start = i+1;
37                 //move pointer 'i' to the next character
38                 i++;
39             }
40         }
41     }
42 }

 

posted @ 2015-10-23 10:48  蟹粉小笼包  阅读(216)  评论(0编辑  收藏  举报