My online accepted solution


  • 0
    K
    public String reverseWords(String s)
    {
        s = s.trim();
        String reversedStr = "";
        String tempStr = "";
        boolean seenWord = false;
        boolean appendSpace = false;
        
        for (int i = s.length()-1; i >= 0; i--)
        {
            if (s.charAt(i) != ' ')
            {
                seenWord = true;
            }
            
            // if seen a word, start constructing strings
            if (s.charAt(i) == ' ' && seenWord)
            {
                appendSpace = true;
                reversedStr += tempStr + " ";
                tempStr = "";
                appendSpace = false;
                seenWord = false;
                continue;
            }
            
            if (seenWord && !appendSpace)
            {
                tempStr = s.charAt(i) + tempStr;
            }
        }
        
        return reversedStr + tempStr;
    }

Log in to reply
 

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