[Java] Beats 99.89% of the solutions. Real Simple code


  • 0
    D

    Pretty self explanatory. I am using the indexOf method for the raw String as it does a linear search internally as well. (Why should I reinvent the wheel ? )

    public class Solution {
        public String reverseWords(String s) {
            if(s ==null) {
                return new String();
            }
            
            char[] myString = s.toCharArray();
            int start=0;
            int lastSpace = s.indexOf(' ', start);
            while(lastSpace != -1) {
                reverseGiven(myString, start, lastSpace -1);
                start = lastSpace+1;
                lastSpace= s.indexOf(' ', start);
            }
            reverseGiven(myString, start, s.length()-1);
            return new String(myString);
        }
        
        public void reverseGiven(char[] input, int start, int end) {
            while(start < end) {
                char temp = input[start];
                input[start] = input[end];
                input[end] = temp;
                start++;
                end--;
            }
        }
    }
    

Log in to reply
 

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