Problem 151:Reverse Words in a String. output "\x00" but "" expected.


  • 0
    Y

    Below is my solution for problem 151. All test cases are passed except for the case of an empty string. My solution gives the output of "\x00", while the expected output is "". Could you help look into this?

    Thanks, and here's my code

    public class Solution {
        public char[] removeSpaces(String s){
            char[] ss = s.toCharArray();
            if(ss.length==0) return ss;
            int shift=0;
            int start=0;
            if(ss[0]==' '){
                shift=1;
                start=1;
            }
            int i = start;
            while(i<ss.length){
                if(ss[i]==' ' && i>0 && ss[i-1]==' '){
                    shift++;
                }else{
                    ss[i-shift]=ss[i];
                }
                i++;
            }
            
            if(ss.length-shift-1<0){
                ss[0]='\0';
                return ss;
            }
            
            if(ss[ss.length-shift-1]==' ') shift++;
            for (int j = ss.length-shift; j < ss.length; j++) {
                ss[j]='\0';
            }
            int ressize = ss.length - shift;
            char[] res = new char[ressize];
            for (int j = 0; j < res.length; j++) {
                res[j]=ss[j];
            }
            return res;
        }
        
        public String reverseWords(String s) {
            if(s.length()<1) return s;
            char[] ss = removeSpaces(s);
            reverseWords(ss);
            return new String(ss);
        }
        public void reverseWords(char[] s) {
            reverse(s, 0, s.length);
            for (int i=0, j=0; j<=s.length; j++) {
                if (j==s.length || s[j]==' ') {
                    reverse(s, i, j);
                    i =  j + 1;
                }
            }
        }
     
        private void reverse(char [] s, int begin, int end) {
            for (int i=0; i<(end-begin)/2; i++) {
                char temp = s[begin+i];
                s[begin+i] = s[end-i-1];
                s[end-i-1] = temp;
            }
        }
    }

Log in to reply
 

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