您的位置:首页 > 编程语言 > Java开发

Reverse Words in a String ---leetcode 我的java题解

2015-04-01 02:53 501 查看
原题连接https://leetcode.com/problems/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.

Clarification:

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。

===================================
分析:最前面和最后面不能是空格。连续多个空格合并成1个空格。

需要考虑特殊情况 Input: "     " 输出应该是""

public class ReverseWordsinAString {
    public void reverse(char[] temp, int start, int end) {
        //逆转字符串
        while (start < end) {
            char t = temp[start];
            temp[start] = temp[end];
            temp[end] = t;
            start++;
            end--;
        }
      }

    public String reverseWords(String s) {
        //先去最前面和最后面的空格
        s = s.trim();
        System.out.println(s);
        int length = s.length();
       char[] temp = new char[s.length()];

        temp = s.toCharArray();

        reverse(temp, 0, length - 1);
        int start = 0;
        int end = 0;
        //以空格为界,处理每组单词
        while (end < length) {
            if (temp[end] == ' ') {
                reverse(temp, start, end - 1);
                start = end + 1;
                end = start;
            }
            if (end == length - 1) {
                reverse(temp, start, end);
                start = end + 1;
                end = start;
            } else end++;
        }

        for(int i=0;i<length;i++)
            System.out.print(temp[i]);
        System.out.println("\n");
        //去掉多余的空格
        int k = 1;
        int i=1;
        while(i<length){
            if (temp[i - 1] == ' ' && temp[i] == ' ')
                i++;
            else {
                temp[k] = temp[i];
                k++;
                i++;
            }
        }

        while(k<temp.length){
            temp[k]=' ';
            k++;
        }

        //return temp.toString();
        //toString() 方法失败,输出乱码[C@1bbe9ba ,要用valueoOf方法
        return (String.valueOf(temp)).trim();
    }

    //测试数据

    public static void main(String[] args) {
       // String mystr = "the sky is     blue";
        String mystr="   a   b  c d   e ";
        // String mystr = "   ";
        ReverseWordsinAString r = new ReverseWordsinAString();
        System.out.println(mystr + "\n");
        System.out.println(r.reverseWords(mystr));
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: