首页 > 解决方案 > 字符串循环旋转的更好方法

问题描述

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

示例输入字符串 = “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;
    }


}

标签: javastring

解决方案


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

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));
}

推荐阅读