noaman_wgs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

【题目】输入“I am a student.”》》》“.tneduts a ma I”。>>输出:student. a am I

 1 package com.exe9.offer;
 2 
 3 /**
 4  * 【题目】“I am a student.”》》》“.tneduts a ma I”。>>student. a am I
 5  * @author WGS
 6  *
 7  */
 8 public class ReverseWordsInSentence {
 9     public void Reverse(char[] str,int begin,int end){
10         if(str==null || str.length<=0) return ;
11         while(begin<=end){
12             char temp=str[begin];
13             str[begin]=str[end];
14             str[end]=temp;
15             begin++;
16             end--;
17         }
18         
19     }
20     
21     public String getReverseSentence(String str){
22         if(str==null || str.length()<=0) return str;
23         char[] charStr=str.toCharArray();
24         //1 先反转整个句子
25         int len=charStr.length;
26         int begin=0;
27         int end=len-1;
28         Reverse(charStr,begin,end);//.tneduts a ma I
29         begin=end=0;
30         
31         //2 反转每个单词
32         while(begin<len){
33             //如果开始就是空格 则为无效字符
34             if(charStr[begin]==' '){
35                 begin++;
36                 end++;
37             }else if(end==len || charStr[end]==' ' ){//当end达到最后一位或者遇到空格,就表示一个单词的结束,就开始反转此单词
38                 Reverse(charStr,begin,--end);
39                 begin=++end;
40             }else{
41                 end++;
42             }            
43         }        
44         return new String(charStr);
45         
46     }
47 
48     public static void main(String[] args) {
49         ReverseWordsInSentence revese=new ReverseWordsInSentence();
50         String str=revese.getReverseSentence("I am a student.");
51         System.out.println(str);
52 
53     }
54 
55 }

 

posted on 2016-06-24 13:54  noaman_wgs  阅读(115)  评论(0)    收藏  举报