Easiest Java Solution (9ms) - Similar to Reverse Words in a String II


  • 12

    I just wanted to use the same logic as Reverse Words in a String II.

    Step 1. Convert the string to char[] array
    Step 2. Whenever I encounter a space ' ' , I call the reverse function ( just to keep the code clean )
    Step 3. Repeat till the end!

    Hope this helps! Thanks for voting :)

    public String reverseWords(String s) 
    {
        char[] s1 = s.toCharArray();
        int i = 0;
        for(int j = 0; j < s1.length; j++)
        {
            if(s1[j] == ' ')
            {
                reverse(s1, i, j - 1);
                i = j + 1;
            }
        }
        reverse(s1, i, s1.length - 1);
        return new String(s1);
    }
    
    public void reverse(char[] s, int l, int r)
    {
    	while(l < r)
    	{
    		char temp = s[l];
    		s[l] = s[r];
    		s[r] = temp;
    		l++; r--;
    	}
    }

  • 7

    No need to add one more reverse before return.

        public String reverseWords(String s) {
            int n = s.length();
            char[] c = s.toCharArray();
            for (int i = 0, j = 1; j <= n; j++) {
                if (j == n || c[j] == ' ') {
                    reverse(c, i, j-1);
                    i = j+1;
                }
            }
            return new String(c);
        }
    
        private void reverse(char[] c, int i, int j) {
            while (i < j) {
                char temp = c[i];
                c[i] = c[j];
                c[j] = temp;
                i++; j--;
            }
        }
    

  • 2

    @Yueyi-Wang Yes your solution will work. But I think my solution will be faster because you are checking (j == n) every time and performing i = j + 1 for the last call which is unnecessary.

    my solution - Run time : 9ms (94.42 %)
    yours - Run time : 10ms (88.72 %)


Log in to reply
 

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