java - 字符串循环旋转的更好方法
问题描述
我编写了一个程序来使用递归生成特定字符串的所有循环旋转。请让我知道我的方法是否正确。请提出对此代码的任何改进。
示例输入字符串 = “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;
}
}
解决方案
如果您不需要使用递归,一种简单的方法可能是这样的:
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));
}
推荐阅读
- elasticsearch - AND 在字符串数组中搜索 Elasticsearch
- c - 试图让计算机猜测我的号码,但获得工作的上限和下限
- oracle - 自治数据库是否提供与本地数据库相同的 NLS 支持?
- c# - 如何在 C# 中使用正则表达式查找和替换较大文件 (150MB-250MB) 中的文本?
- c# - C#调用基接口的默认实现
- java - Java awt not shown in eclipse
- python - Values on dataframe dont appear with decimals
- sql - 如何计算数组GBQ中的重复值?
- mysql - MySQL master pushes old bin log after Heartbeat event
- python - 在 Python 中使用 SAX 解析器的标签之间的文本