My accepted Java solution [needs simplification]


  • 0
    F

    Hello community,

    I have written an accepted Java solution which takes the following steps:

    • filtering s from leading, trailing and duplicated spaces
    • reversing a filtered s
    • reversing each word in the reversed string

    But it looks too complicated to me and performance isn't so high as I expected.

    Could you please suggest me any ideas how to simplify my solution and make it faster.

    Thanks in advance.

    public class Solution {
    
        public String reverseWords(String s) {
            int length = s.length();
            char[] chars = new char[length];
    
            // filtering s from leading, trailing and duplicated spaces
            int filteredLength = 0;
            int beginningOfWord = 0;
            int endOfWord = 0;
            while (beginningOfWord < length && s.charAt(beginningOfWord) == ' ') {
                beginningOfWord++;
            }
            while (beginningOfWord < length) {
                endOfWord = beginningOfWord;
                while (endOfWord < length && s.charAt(endOfWord) != ' ') {
                    endOfWord++;
                }
    
                while (beginningOfWord < endOfWord) {
                    chars[filteredLength++] = s.charAt(beginningOfWord++);
                }
    
                beginningOfWord = endOfWord;
                while (beginningOfWord < length && s.charAt(beginningOfWord) == ' ') {
                    beginningOfWord++;
                }
    
                if (beginningOfWord < length) {
                    chars[filteredLength++] = ' ';
                }
            }
    
            // reversing a filtered s
            for (int i = 0; i < filteredLength / 2; i++) {
                swap(chars, i, filteredLength - i - 1);
            }
    
            // reversing each word in the reversed string
            beginningOfWord = 0;
            while (beginningOfWord < filteredLength) {
                endOfWord = beginningOfWord;
                while (endOfWord < filteredLength && chars[endOfWord] != ' ') {
                    endOfWord++;
                }
                int lengthOfWord = endOfWord - beginningOfWord;
                for (int i = 0; i < lengthOfWord / 2; i++) {
                    swap(chars, beginningOfWord + i, endOfWord - i - 1);
                }
    
                beginningOfWord = endOfWord + 1;
            }
    
            return new String(chars, 0, filteredLength);
        }
    
        private void swap(char[] chars, int i, int j) {
            char tmp = chars[i];
            chars[i] = chars[j];
            chars[j] = tmp;
        }
    
    }

Log in to reply
 

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