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

lintcode53 Reverse Words in a String -easy

时间:2017-09-11 14:16:17      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:contain   mile   pac   solution   rac   for   write   tween   not   

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

标签:contain   mile   pac   solution   rac   for   write   tween   not   

原文地址:http://www.cnblogs.com/jasminemzy/p/7504633.html

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