0%

leetCode-151:Reverse Words in a String

问题描述

给定一个字符串,由单词和空格组成,要求将字符串中单词进行倒序(单词间用一个空格分隔)。题目链接:**点我**

样例输入输出

输入:” Bob Loves Alice “

输出:”Alice Loves Bob”

输入:”a good example”

输出:”example good a”

问题解法

解法一

使用 split 函数对字符串按空格分隔,然后从后往前拼接字符串。这种做法简单,但是消耗空间比较多。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution
{
public String reverseWords(String s)
{
if (s == null || s.length() == 0)
{
return s;
}

String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--)
{
if (words[i].length() > 0)
{
sb.append(words[i]).append(" ");
}
}

sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}

解法二

从后往前遍历字符串,遇到非空格的字符,则从此处向前查找最后一个空格,然后切割出单词进行拼接。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution
{
public String reverseWords(String s)
{
if (s == null || s.length() == 0)
{
return s;
}

StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; i--)
{
if (s.charAt(i) != ' ')
{
int spaceIndex = s.lastIndexOf(' ', i);
sb.append(s.substring(spaceIndex + 1, i + 1)).append(" ");
i = spaceIndex;
}
}

sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}