[Lintcode]Reverse Words in a String

来源:互联网 发布:企业管理优化建议 编辑:程序博客网 时间:2024/06/08 12:15

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

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

return "blue is sky the".

两个指针,每次遇到空格进行判定是否插入新单词并初始化index。Leading space会由于start=-1而避免。多个空格的情况同样。 最后处理tailing space即可。


public class Solution {    /**     * @param s : A string     * @return : A string     */    public String reverseWords(String s) {        StringBuilder res = new StringBuilder();        char[] array = s.toCharArray();        int start = -1, end = -1;                for(int i = 0; i < array.length; i++) {                        char c = array[i];                        if(c == ' ') {                //detected a word                if(start != -1) {                    end = i;                    res.insert(0, s.substring(start, end));                    res.insert(0, " ");                                            //re-init                    start = -1;                    end = -1;                }            }            else {                if(start == -1) start = i;            }        }                if(start != -1) res.insert(0, s.substring(start));//add last word when have not trailing space        if(res.length() > 0 && res.charAt(0) == ' ') res.deleteCharAt(0);//remove leading space        return res.toString();    }}


0 0
原创粉丝点击