Reverse Words In a String

这题简单的话用split函数就行了,但要注意split的用法是很奇怪的,


Reverse Words In a String_第1张图片
split.png
    public String reverseWords(String s) {
        String[] array = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = array.length - 1; i >= 0; i--) {
//这一行用""作regex,而不是" ",因为array里根本没有" "了
            if (!array[i].equals("") ) {
                sb.append(array[i]).append(" ");
            }
            //这样写的话就忽略了" 1"这种情况
            // if (i != 0) {
            //     sb.append(" ");
            // }
        }
        return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
    }

摘抄递归做法:
http://blog.csdn.net/linhuanmars/article/details/20982463

public String reverseWords(String s) {
    s = s.trim();
    return helper(s,0).toString();
}
private StringBuilder helper(String s, int index)
{
    if(index>=s.length())
        return new StringBuilder(); 
    StringBuilder cur = new StringBuilder();
    int lastIndex = index;
    while(index < s.length() && s.charAt(index)!=' ')
    {
        cur.append(s.charAt(index++));
    }
    while(index < s.length() && s.charAt(index)==' ')
        index++;
    if(lastIndex == 0)
        return helper(s,index).append(cur);
    return helper(s,index).append(cur).append(' ');
}

还有种方法,先反转成"eulb si yks eht",然后在对每一个单词反转,得到"blue is sky the"。不写了。

你可能感兴趣的:(Reverse Words In a String)