2 methods in Java - charArray and String Builder


  • 0
    C

    The uncommented code is with the char array method while the commented code is with using StringBuilder. This might be a good side-by-side comparison for anyone new to Java and learning about different methods of operating with Strings.

    Even though time and space complexity are the same for these methods, the char[] is faster because it is utilizing core primitive type, char. On the other hand, StringBuilder is a special class that has higher complexity.

    This is one of my first few posts. Any feedback is appreciated!

        public String reverseWords(String s){
            //Time - O(n^2)
            //Space - O(n) - the return string
            //--> where n is the length of the string
            
            if(s == null){
                return null;
            }
            
            char[] sArray = s.toCharArray();
            int begin = 0;
            
            for(int i = 0; i < sArray.length; i++){
                if(sArray[i] == ' '){
                    addWordReverse(sArray, begin, i - 1);
                    begin = i + 1;
                } else if(i == s.length() - 1){
                    addWordReverse(sArray, begin, i);
                }
            }
            
            return new String(sArray);
        }
        
        private void addWordReverse(char[] sArray, int begin, int end){
            while(begin < end){
                char temp = sArray[begin];
                sArray[begin] = sArray[end];
                sArray[end] = temp;
                
                begin = begin + 1;
                end = end - 1;
            }
        }
        
        
    /*    public String reverseWords(String s) {
            //Time - O(n^2)
            //Space - O(n) - the return string
            //--> where n is the length of the string
            
            if(s == null){
                return null;
            }
            
            StringBuilder sBuilder = new StringBuilder();
            int begin = 0;
            
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) == ' '){
                    addWordReverseSB(s, sBuilder, begin, i - 1);
                    sBuilder.append(" ");
                    begin = i + 1;
                } else if(i == s.length() - 1){
                    addWordReverseSB(s, sBuilder, begin, i);
                }
            }
            
            return sBuilder.toString();
        }
        
        private void addWordReverseSB(String s, StringBuilder sBuilder, int begin, int end){
            for(int i = end; i >= begin; i--){
                sBuilder.append(s.charAt(i));
            }
        }*/
    

Log in to reply
 

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