LeetCode problem#557
Reverse Words in a String III
Solved in 1 languageJava
Solution
22 lines
1class Solution {
2 public String reverseWords(String s) {
3 StringBuilder sb = new StringBuilder();
4
5 String wordSoFar = "";
6 for (int i = 0; i < s.length(); i++) {
7 if (s.charAt(i) == ' ') {
8 sb.append(wordSoFar);
9 sb.append(s.charAt(i));
10 wordSoFar = "";
11 }
12 else {
13 wordSoFar = s.charAt(i) + wordSoFar;
14 }
15 }
16 if (wordSoFar.length() > 0) {
17 sb.append(wordSoFar);
18 }
19
20 return sb.toString();
21 }
22}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.