Java Simple Solution


  • 1
    S

    Find the " " and swap the substring, 14ms solution

        public String reverseWords(String s) {
            char[] c = s.toCharArray();
            int i = 0, j = 0;
            for(char cc: s.toCharArray()) {
                if(cc == ' ') {
                    int end = j-1; 
                while(i<end) {
                    char temp = c[i];
                    c[i] = c[end];
                    c[end] = temp;
                    end--;
                    i++;
                }
                i = j+1;
                } else if (j == s.length()-1) {
                    int end = j; 
                while(i<end) {
                    char temp = c[i];
                    c[i] = c[end];
                    c[end] = temp;
                    end--;
                    i++;
                }
                i = j+1;
                }
                j++;
            }
            return new String(c);
        }
    

  • 1
    S

    I think this is simpler:

        public String reverseWords(String s) {
            return Arrays.stream(s.split("\\s+"))
                         .map(StringBuilder::new)
                         .map(StringBuilder::reverse)
                         .collect(Collectors.joining(" "));
        }
    

  • 0
    J

    @szabados so cool !


Log in to reply
 

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