字符串-Reverse Words in a String(翻转字符串)

问题描述:

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

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

思考:

关键在于对空格的剔除和对字符串的索引的把握,思路就是使用一个result字符串类累加保存结果,把顺序寻找的字符串添加在result的0位置上,那么后面的索引向后向后全部移动新字符串长度。

代码(java):

public class Solution {
    public String reverseWords(String s) {
        
        int begin = 0;  
        int end   = 0; 
        
        if(s==null) {  
            return s;  
        }  
         
        while(begin<s.length()&&s.charAt(begin)==' ') {  
            begin++;  
        }  
        if(begin==s.length()) {  
            return "";  
        }  
          
        if(s.length()<=1) {  
            return s;  
        }  
        StringBuilder result = new StringBuilder("");  
        while(begin<s.length()&&end<s.length()) {  
            while(begin<s.length()&&s.charAt(begin)==' ') {  
                begin++;  
            }  
            if(begin==s.length()) {  
                break;  
            }  
            end = begin + 1;  
            while(end<s.length()&&s.charAt(end)!=' ') {  
                end++;  
            }  
            if(result.length()!=0) {  
                result.insert(0," ");  
            }  
            if(end<s.length()) {  
                result.insert(0,s.substring(begin,end));  
            } else {  
                result.insert(0,s.substring(begin,end));  
                break;  
            }  
            begin = end + 1;  
        }  
        return result.toString();  
    }
}
点赞