天天看點

筆試題-反轉字元串和按單詞反轉字元串

反轉一個字元串,例如:abcdefg gfedcba

反轉字元串,按單詞操作,例如_how_____are__you 反轉之後you__are_____how_

class StringReverse 
{
    public static void main(String[] args) 
    {
        System.out.println(reverse1("____how_____are__you_"));
        System.out.println(reverse2("____how_____are__you_"));
        System.out.println(wordReverse("____how_____are__you_"));
    }

    //反轉一個字元串 
    //方法一:通過str建構StringBuffer執行個體,調用StringBuffer的reverse方法
    public static String reverse1(String str){
        //StringUtil.reverse(str);
        StringBuffer sb = new StringBuffer(str);
        return sb.reverse().toString();
    }
    //反轉一個字元串
    //方法二:通過字元數組 首尾交換
    public static String reverse2(String str){
        char[] chs = str.toCharArray();
        for(int i = 0, j = chs.length-1; i < j; i++,j--){
            swap(chs,i,j);
        }
        return new String(chs);
    }
    //給出一個字元串,将其按單詞反轉
    // 如____how_____are__you_ 反轉之後_you__are_____how____
    public static String wordReverse(String str){
        char[] chs = str.toCharArray();
        reverse(chs,0,chs.length-1);
        int start = 0;
        for(int i = 0 ; i < chs.length; i++){
            if(chs[i] == '_'){
                if(i == 0){
                    start++;
                    continue;
                }
                swap(chs,start,i-1);
                start = i+1;
            }
        }
        reverse(chs,start,chs.length-1);
        return new String(chs);
    }

    //根據首末位置,反轉數組
    public static void reverse(char[] chs,int start,int end){
        while(start < end){
            swap(chs,start,end);
            start++;
            end--;
        }
    }

    //互換位置
    public static  void swap(char[] arr,int i,int j){
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
           

繼續閱讀