12 ms Java solution with explanation


  • 0
    L

    The idea is simple:

    1. Get past the spaces at the start and record that index as the start (s)
    2. Get past the non-spaces and record that index as the end (k)
    3. Swap from s to k.
    4. move e till the end of the sentence.
       public String reverseWords(String str)
      {
        char[] arr = str.toCharArray();
        for (int e = 0, s = 0; e < arr.length;) {
          while (e < arr.length && arr[e] == ' ') {
            e++;
          }
          s = e;//past spaces.
          while (e < arr.length && arr[e] != ' ') {
            e++;
          }
          int k = e - 1; //beyond the boundary.
          while (k > s) {
            char c = arr[k];
            arr[k] = arr[s];
            arr[s] = c;
            k--;
            s++;
          }
        }
        return new String(arr);
      }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.