Skip to content

557. Reverse Words in a String III 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  string reverseWords(string s) {
    int i = 0;
    int j = 0;

    while (i < s.length()) {
      while (i < j || i < s.length() && s[i] == ' ')
        ++i;
      while (j < i || j < s.length() && s[j] != ' ')
        ++j;
      reverse(begin(s) + i, begin(s) + j);
    }

    return s;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public String reverseWords(String s) {
    StringBuilder sb = new StringBuilder(s);
    int i = 0;
    int j = 0;

    while (i < sb.length()) {
      while (i < j || i < sb.length() && sb.charAt(i) == ' ')
        ++i;
      while (j < i || j < sb.length() && sb.charAt(j) != ' ')
        ++j;
      reverse(sb, i, j - 1);
    }

    return sb.toString();
  }

  private void reverse(StringBuilder sb, int l, int r) {
    while (l < r) {
      final char temp = sb.charAt(l);
      sb.setCharAt(l++, sb.charAt(r));
      sb.setCharAt(r--, temp);
    }
  }
}