Coding interview:字符串反转

首先对整个句子反转,然后对其中每一个单词进行反转。

void swap(char[]sentence,int i,int j){
        char c = sentence[i];
        sentence[i] = sentence[j];
        sentence[j] = c;
    }

    void reverse(char[]sentence,int begin,int end){
        while(begin<end){
            swap(sentence,begin,end);
            begin++;
            end--;
        }
    }

    void reverseSentence(char[]sentence){

        int len = sentence.length;
        reverse(sentence,0,len-1);

        int begin = 0;

        for(int i=0;i < len;i++){
            if(sentence[i]==' '){
                reverse(sentence,begin,i-1);
                begin = i+1;
            }
        }

        reverse(sentence,begin,len-1);
    }

    public static void main(String[]args){
        ReverseSentence reverseSentence = new ReverseSentence();
        char[] str = "I am zhumingyuan , age is 10".toCharArray();
        reverseSentence.reverseSentence(str);
        System.out.println(str);
    }

猜你喜欢

转载自blog.csdn.net/zhumingyuan111/article/details/80210745