Alg.16 Reverse Words In String

From algoexpert.io

In this problem, given a string of words seperated by one or more whitespaces. We need to write a function reverse these words. Basically, the idea is seperate all the words by the whitespaces. Then, we simply reverse them. Here is the implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public String reverseWordsInString(String string) {
List<String> words = new ArrayList<>();
int curStart = 0;
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (c == ' ') {
words.add(string.substring(curStart, i));
words.add(" ");
curStart = i + 1;
} else {
continue;
}
}
words.add(string.substring(curStart));
Collections.reverse(words);
return String.join("", words);
}

Another way is to first reverse all the characters within this string, then we reverse each string back.

Time complexity: O(n); Space complexity: O(n)

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2021 Zirun Lin

Thanks~

支付宝
微信