字符串循环旋转的更好方法

时间:2018-12-02 05:01:34

标签: java string

我编写了一个程序,以使用递归生成特定字符串的所有循环旋转。请让我知道我的方法是否正确。请提出对此代码的任何改进。

示例 输入字符串=“ abcd”

输出:

abcd BCDA cdab dabc

public class CyclicRotationOfString {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s = "abcd";
        String orig =s;
        //cyclicRotate(s, orig); //approach 1
        cyclicRotate(s, s.length()); //approach 2
    }

    //approach 1    
    public static String cyclicRotate(String s, String orig) {
        String ns=null;
        StringBuffer sb = new StringBuffer(s.substring(1));
        sb.append(s.charAt(0));
        ns = sb.toString(); 
        System.out.println(s);
        if(ns.equals(orig)) {
            return ns;
        }
        cyclicRotate(ns,orig);
        return ns;
    }

    //approach 2
    public static String cyclicRotate(String s, int len) {
        len--;
        StringBuffer sb = new StringBuffer(s.substring(1));
        sb.append(s.charAt(0));
        String ns = sb.toString(); 
        System.out.println(s);
        if(len==0) {
            return ns;
        }
        cyclicRotate(ns,len); //break out after comparing the string
        return ns;
    }


}

1 个答案:

答案 0 :(得分:0)

如果您不需要使用递归,则一种简单的方法可能是这样的:

public static void main(String[] args) {
    String original = "abcd", d = original;
    do {
        System.out.print(d + " ");
    }
    while(!(d = (d.substring(1) + d.charAt(0))).equals(original));
}