JAVA no with and without StringBuilder solutions


  • 0
    K

    With StringBuilder:

    public class Solution {
        public String reverseWords(String s) {
            StringBuilder sb = new StringBuilder(s.length());
            StringBuilder temp = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == ' ') {
                    if (sb.length() != 0) sb.append(' ');
                    sb.append(temp.reverse().toString());
                    temp = new StringBuilder();
                }
                else {
                    temp.append(s.charAt(i));
                }
            }
            if (temp.length() != 0)
                if (sb.length() != 0) sb.append(" ");
                sb.append(temp.reverse().toString());
            return sb.toString(); 
        }
    }
    

    Without StringBuilder and without additional memory (like String[])

    public class Solution {
        public String reverseWords(String s) {
            char[] array = new char[s.length()];
            for (int i = 0, k = 0; k <= s.length(); k++) {
                if (k == s.length()) {
                    reverse(array, i, k);
                    break;
                }
                if (s.charAt(k) == ' ') {
                    reverse(array, i, k);
                    array[k] = ' ';
                    i = k + 1;
                } else {
                    array[k] = s.charAt(k);
                }
            }
            return new String(array);
        }
    
        private void reverse(char[] array, int start, int end) {
            for (int i = start, l = 0; i < (end + start) / 2; i++, l++) {
                char t = array[i];
                array[i] = array[end - 1 - l];
                array[end - 1 - l] = t;
            }
        }
    }
    

Log in to reply
 

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