leetcode 151. Reverse Words in a String --------- java

来源:互联网 发布:免费翻墙安卓软件 编辑:程序博客网 时间:2024/06/06 08:23

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

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

解题思路:

本题方法多多,最简单的方式直接按“ ” spilt即可,JAVA实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
public String reverseWords(String s) {
    if (s == null || s.length() == 0)
        return s;
    String[] str = s.split(" ");
    StringBuilder sb = new StringBuilder();
    for (int i = str.length - 1; i >= 0; i--)
        if (str[i].length() >= 1)
            sb.append(str[i] + " ");
    if (sb.length() > 1)
        sb.deleteCharAt(sb.length() - 1);
    return sb.toString();
}
0 0
原创粉丝点击