翻轉字符串

import com.sun.deploy.util.StringUtils;

/**
 * Created by lifei on 16/5/25.
 *
 *
 I am a student 中國
 中國 student a am I

 先將每一個單詞反轉,再將總體字符串反轉
 或者
 先將總體字符串反轉,再每一個單詞反轉
 */
public class ReverseWords {

    static String word;

    public ReverseWords(String word) {
        this.word = word;
    }

    public static void main(String[] args) {
        ReverseWords rw = new ReverseWords("I love you");
//        ReverseWords rw = new ReverseWords("I am a student 中國");
        System.out.println(word);
        rw.reverseWords();
        System.out.println(word);


    }

    private void reverseWords() {
        int length = word.length();
        int begin = -1;
        int end = -1;
        for (int i = 0; i < length; i++){
            if (begin == -1 && word.charAt(i) == ' '){
                continue;
            }
            if (begin == -1){
                begin = i;
                continue;
            }
            if (word.charAt(i) == ' '){
                end = i - 1;
            } else if (i == length -1){
                end = i;
            } else {
                continue;
            }
            reverse(begin,end);
            begin = -1;
            end = -1;
        }
        reverse(0,length-1);
    }

    private void reverse(int begin, int end) {
        char[] tmp = word.toCharArray();
        while (begin < end){
            tmp[begin] ^= tmp[end];
            tmp[end] ^= tmp[begin];
            tmp[begin] ^= tmp[end];
            begin++;
            end--;
        }
        word = String.copyValueOf(tmp);
    }
}



/**
 *
 */
public class ReverseWords2 {

    static char[] chars;

    public ReverseWords2(String word) {
        this.chars = word.toCharArray();
    }

    void reverseWord(){
        int begin = 0;
        int end = 0;
        for (int i = 0; i<chars.length;i++){
            if (begin == -1 && chars[i] == ' '){
                continue;
            }
            if (begin == -1){
                begin = i;
                continue;
            }
            if (chars[i] == ' '){
                end = i - 1;
            } else if (i == chars.length -1){
                end = i;
            } else {
                continue;
            }
            reverse(begin,end);
            begin = -1;
            end = -1;
        }
        reverse(0,chars.length-1);
    }

    private void reverse(int start, int end) {
        while (start < end){
            char tmp = chars[start];
            chars[start] = chars[end];
            chars[end] = tmp;
            start++;
            end--;
        }
    }


    public static void main(String[] args) {
        ReverseWords2 rw2 = new ReverseWords2("I love you");
        rw2.reverseWord();
        System.out.println(String.valueOf(chars));
    }
}
相關文章
相關標籤/搜索