Simple Java solution with explanation


  • 0
    L

    Pay attention to the clarification as it mentions that the spaces at the start and end can be discarded. Also, multiple spaces between different words can be collapsed to a single space. The later part made think to do that in the first pass of the string so that it is easier to remove the multiple spaces in between the words. So the idea is to create a stringbuilder object and then get rid of multiple spaces , reverse it as a whole and then reverse per word.

    To avoid the code to become clumsy, use a start and an end pointer where start takes care of going past spaces and the end takes care of going start the word. At the end just swap them.

      public String reverseWords(String s)
      {
        s = s.trim();
        if (s.length() == 0)
        {
          return s;
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < s.length(); i++)
        {
          char c = s.charAt(i);
          if (c == ' ')
          {
            while (i < s.length() && s.charAt(i) == ' ')
            {
              i++;
            }
            i--;
          }
          builder.append(c);
        }
        int n = builder.length();
        // First, reverses the whole string.
        reverse(builder, 0, n - 1);
        // Second, Reverses each word in the string.
        int start = 0, end = 0;
        while (start < n)
        {
          while (start < end || start < n && builder.charAt(start) == ' ')
          {
            ++start; // Skip spaces chars.
          }
          while (end < start || end < n && builder.charAt(end) != ' ')
          {
            ++end; // Skip non-spaces chars.
          }
          reverse(builder, start, end - 1);
        }
        return builder.toString();
      }
    
    
    
      public static void reverse(StringBuilder builder, int start,
          int end)
      {
        while (start < end)
        {
          char tmp = builder.charAt(start);
          builder.setCharAt(start++, builder.charAt(end));
          builder.setCharAt(end--, tmp);
        }
      } 
    

Log in to reply
 

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