1. 程式人生 > >lintcode53 Reverse Words in a String -easy

lintcode53 Reverse Words in a String -easy

ini rds util 輸入 while -s lead 子字符串 returns

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

    • 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

import java.util.Stack;
public class Solution {
    /*
     * @param s: A string
     * @return: A string
     */
    public String reverseWords(String s) {
        // write your code here
        
        if
(s == null){ return null; } if(s.length() == 0){ return new String(); } Stack<String> stack = new Stack<String>(); int head = 0; int tail = 0; while(head < s.length()){
while(head < s.length() && s.charAt(head) == ){ head++; } tail = head; while(tail < s.length() && s.charAt(tail) != ){ tail ++; } if(head >= s.length() || tail > s.length()){ break; } stack.push(s.substring(head, tail)); head = tail; } String reversed = new String(); while (!stack.isEmpty()){ reversed += stack.pop(); reversed += " "; } if(reversed.length() > 0){ reversed = reversed.substring(0, reversed.length() -1); } return reversed; } }

1. str.substring(int, int); 而不是str.subString(int, int);
2. substring(int beginIndex,int endIndex)從指定的 beginIndex 處開始,直到索引 endIndex - 1 處的字符。因此,該子字符串的長度為 endIndex-beginIndex。 "smiles".substring(1, 5) returns "mile"
3. 在塞完所有單詞到stack裏後,最後一個個拿出來打印的時候,切記切記循環體for()裏面不可以是int i = 0; i < stack.size(); i++!,因為你for{}裏面的操作有在pop,那你等於size這個值就一直在變!可以

int wordCount = stack.size();
if(!stack.isEmpty()){
  for(int i = 0; i < wordCount - 1; i++){
    reversed+= stack.pop();
    reversed+= " ";
  }
  reversed += stack.pop();
}

或者

while (!stack.isEmpty()){
            reversed += stack.pop();
            reversed += " ";
        }
        if(reversed.length() > 0){
            reversed = reversed.substring(0, reversed.length() -1);
        }
}

4.註意關註輸入處理,null, "", " "。在心裏跑一下他們

lintcode53 Reverse Words in a String -easy