码迷,mamicode.com
首页 > 其他好文 > 详细

Q2:Reverse Words in a String

时间:2014-11-26 20:37:05      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   java   for   strong   

Clarification:

    • What constitutes a word?
      A sequence of non-space characters constitutes a word.
    • Could the input string contain leading or trailing spaces?
      Yes. However, your reversed string should not contain leading or trailing spaces.
    • How about multiple spaces between two words?
      Reduce them to a single space in the reversed string.

 

MyAnswer 1 (Java):

 1 public class Solution {
 2     public String reverseWords(String s) {
 3         String result = "";
 4         int i = 0;
 5         int j = s.length();
 6         for(i = s.length()-1; i >= 0; i--)
 7         {
 8             if(s.charAt(i) == ‘ ‘)
 9             {
10                 if(i == s.length()-1)
11                 {
12                     j = i;
13                     //continue;
14                 }
15                 else if(i == 0)
16                 {
17                     //i++;
18                     break;
19                 }
20                 else if(j == i+1)
21                 {
22                     j = i;
23                     //continue;
24                 }
25                 else
26                 {
27                     result = result.concat(s.substring(i+1,j)+" ");
28                     j = i;
29                 }
30             }
31         }
32         result = result.concat(s.substring(i+1,j));
33         if(!result.isEmpty() && result.charAt(result.length()-1) == ‘ ‘)
34             result = result.substring(0,result.length()-1);
35         return result;
36     }
37 }

 使代码更加精简,改为:

MyAnswer 2(Java):

 1 public class Solution {
 2     public String reverseWords(String s) {
 3         
 4         String result = "";
 5         int j = s.length();
 6         int i = j-1;
 7         
 8         for(; i >= 0; i--)
 9         {
10             if(s.charAt(i) == ‘ ‘)
11             {
12                 if(i == 0)
13                 {
14                     break;
15                 }
16                 else if(i != s.length()-1 && j != i+1)
17                 {
18                     result = result.concat(s.substring(i+1,j)+" ");
19                 }
20                 j = i;
21             }
22         }
23         
24         result = result.concat(s.substring(i+1,j));
25         
26         int k = result.length();
27         if(!result.isEmpty() && result.charAt(k-1) == ‘ ‘)
28             result = result.substring(0,k-1);
29         return result;
30     }
31 }

 

Q2:Reverse Words in a String

标签:style   blog   io   ar   color   sp   java   for   strong   

原文地址:http://www.cnblogs.com/ISeeIC/p/4124752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!