翻转字符串,想到什么写什么。。。
我的做法是先trim掉空格,然后从字符串尾部开始扫描,遇到空格则认为一个单词结束,然后copy这个单词。
需要注意的地方在于当扫描到最后一个单词的第一个字母时(譬如the sky is blue的t字母),注意单词长度的自增逻辑。
网上还有人的做法是反转整个字符串,然后逐个翻转单词。
1 package edu.hust.sse.Problems;
2
3 //Given s = "the sky is blue",
4 //return "blue is sky the".
5 /***
6 * author @Ivan July 16th,2014
7 * @param s
8 * @return
9 */
10 public class ReverseWordsInString {
11 public static void main(String[] args){
12 ReverseWordsInString rw = new ReverseWordsInString();
13 rw.reverseWords(" abc test teacher ");
14 }
15
16 public String reverseWords(String s) {
17 s = s.trim();
18 if(s.length() == 0){
19 return "";
20 }
21 byte[] a = s.getBytes();
22 byte[] b = new byte[a.length];
23
24 int startPos = 0;
25 int wordLen =0;
26 int bStart = 0;
27 boolean addSpace = false;
28 for(int i= a.length- 1;i>=0;i--){
29
30 if(a[i] == 32 ){
31 //copy a word and add a space
32 if(wordLen >0){
33
34 //Need add space from the second word
35 if(addSpace){
36 b[bStart] = 32;
37 bStart ++;
38 }
39
40 if(i == 0){
41 startPos = i;
42 }else{
43 startPos = i+1;
44 }
45 for(int j=startPos;j<=i+wordLen;j++){
46 b[bStart] = a[j];
47 bStart ++;
48 }
49
50 //set initial parameter for the next word
51 addSpace = true;
52 wordLen = 0;
53 }
54
55 }
56 //need to continue to scan a complete word
57 else{
58 wordLen ++;
59 if(i==0){
60 //Need add space from the second word
61 if(addSpace){
62 b[bStart] = 32;
63 bStart ++;
64 }
65
66 for(int j=0;j<i+wordLen;j++){
67 b[bStart] = a[j];
68 bStart ++;
69 }
70 }
71 }
72 }
73
74 // System.out.println(new String(b));
75 return new String(b).trim();
76
77 }
78 }