二、翻转字符串

时间:2022-04-16 11:17:16

通过求逆来翻转字符串

题目及思路来源自《编程珠玑》 2.3

题目

将一个字符串某一位之前的所有元素移到队尾。

原字符串 定位 移动后字符串
abcdefghijklmnopqrstuvwxyz 5 fghijklmnopqrstuvwxyzabcde
abcdefghijklmnopqrstuvwxyz 10 klmnopqrstuvwxyzabcdefghij

方法

翻手法,亦即向量求逆。
s = a + b
a = abcd;
a' = bcda;
翻转后
s1 = s' = (a' + b')'

代码

public class VectorRotate {
    private String str ;
    private String fStr;
    private String lStr;
    
    public VectorRotate(int i){
        str = "abcdefghijklmnopqrstuvwxyz";
        fStr = str.substring(0, i);
        lStr = str.substring(i);
    }
    
    public String sWap(String s){
        String as = "";
        for(int i = s.length()-1; i >=0 ;i--){
            as += s.charAt(i)+"";
        }
        return as;
    }
    
    public static void main(String[] args) {
        int i = 10;
        System.out.println(vr.sWap(vr.sWap(vr.fStr) + vr.sWap(vr.lStr)));
    }
}

运行

  1. 原字符串:"abcdefghijklmnopqrstuvwxyz"
    位置:5
    转换后
    二、翻转字符串

  2. 原字符串:"abcdefghijklmnopqrstuvwxyz"
    位置:10
    转换后
    二、翻转字符串

连续执行一百万次

long time = System.currentTimeMillis();
for(int j=0;j<1000000;j++)
vr.str = vr.sWap(vr.sWap(vr.fStr) + vr.sWap(vr.lStr));
time = System.currentTimeMillis() - time;
        
System.out.println(vr.str+" time: "+time+"ms");

输出
二、翻转字符串

字符串有十万位

public VectorRotate(int i,int k){
    //10000*10 = 100000
    str = "";
    for(int j = 0; j<10000 ; j++)
        str += "abcdefghij";
    fStr = str.substring(0, i);
    lStr = str.substring(i);
    }

输出
二、翻转字符串

分析

在求字符串的逆时浪费了过多的时间,导致结果并不是很理想,在有10万位时速度明显降低。求逆算法待优化。

waiting for version 2.0