Sword Finger Offer Interview Question 58: Reverse String

I made it myself, but the code is verbose

After reading Jianzhi Offer's answer code, it is similar to my idea, but because the book does not say that multiple spaces are treated as one space, his implementation is not very desirable.

Something to pay attention to

char[] s_c_old = s.toCharArray();
StringBuilder res = new StringBuilder();
res.append(s_c[count_in]);
String res_s = res.toString();

 

My code

    public String reverseWords(String s) {
        char[] s_c_old = s.toCharArray();
        int new_length = s_c_old.length;
        int count = 0;
        int start_index = count;
        for(;start_index<s_c_old.length;start_index++){
            if(s_c_old[start_index] == ' '){
                new_length--;
            }else{
                break;
            }
        }
        int last_index = s_c_old.length - 1;
        for(;last_index>=0;last_index--){
            if(s_c_old[last_index] == ' '){
                new_length--;
            }else{
                break;
            }
        }
        for(count = start_index;count<=last_index;count++){
            if(count > 0){
                if(s_c_old[count] == ' '&&s_c_old[count-1] == ' '){
                    new_length--;
                }
            }
            
        }
        if(new_length<=0){
            return "";
        }
        char[] s_c = new char[new_length];
        int s_c_count = 0;
        for(count = start_index ;count<=last_index;count++){
            if(count > start_index){
                if(s_c_old[count]!=' '&&s_c_old[count-1]==' '){
                    s_c[s_c_count++] = ' ';  
                    s_c[s_c_count++] = s_c_old[count];    
                }else if(s_c_old[count]!=' '&&s_c_old[count-1]!=' '){
                    s_c[s_c_count++] = s_c_old[count];
                }
            }else{
                if(s_c_old[count]!=' '){
                    s_c[s_c_count++] = s_c_old[count];    
                }
            }
            
            
        }

        StringBuilder res = new StringBuilder();
        for(int count_out = s_c.length - 1;count_out >=0;count_out--){
            if(s_c[count_out]==' '){
                for(int count_in = count_out + 1;count_in < s_c.length&&s_c[count_in]!=' ';count_in++){
                    res.append(s_c[count_in]);
                }
                res.append(' ');
            }
        }
        for(int count_in = 0;count_in < s_c.length&&s_c[count_in]!=' ';count_in++){
            res.append(s_c[count_in]);
        }

        String res_s = res.toString();
        return res_s;
    }

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/115103125