Java不使用其他函数,将字符串按照给定规则进行反转

要求:给予字符串是类似于网址:www.baidu.com   或者  www.sina.com.cn
           将给与的字符串按照规则反转 com.baidu.www  /  cn.com.sina.www

package 基础算法;

public class TEST {
    /**
     * 给予字符串是类似于网址:www.baidu.com    www.sina.com.cn
     * 将给与的字符串按照规则反转 com.baidu.www    cn.com.sina.www
     * @param str
     * @return
     */
    public static String allRotate(String str){
        int strLength = str.length();
        char[] chars = str.toCharArray();
        int left = 0;
        // 先局部反转
        for (int i = 0; i < strLength; i++){
            if (chars[i] == '.'){
                Rotate(chars, left, i-1);
                left = i + 1;
            }
        }
        Rotate(chars, left, strLength-1);  // 最后一小段反转
        Rotate(chars,0,strLength-1);  // 整体反转
        return new String(chars);
    }
    public static void Rotate(char[] chars, int start, int end){
        while (start < end){
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        String str = "www.baidu.com";
        System.out.println(allRotate(str));

    }

}

猜你喜欢

转载自blog.csdn.net/m0_38109046/article/details/88949809
今日推荐