【发布时间】:2021-10-17 05:43:56
【问题描述】:
问题
给定 word 如果没有按字母顺序排列的更大排列,则返回该单词的所有排列中按字母顺序排列的下一个较大的字符串返回“无答案”
例子
单词 = "baca"
所有按字母顺序排列的排列都是“aabc”、“abac”......还有更多。
我们需要在单词“baca”之后找到下一个按字母顺序更大的排列,那就是“bcaa”
“单词”的长度在 2 到 10^4 个字符之间。
我的问题
我的算法,能找到相关的词,但是太慢了(Stackoverflow由于递归调用太多)
我的方法
- 找到所有排列并将它们添加到列表中
- 按字母顺序对上述列表进行排序
- 在列表中搜索“单词”并返回该单词之后的下一个元素,如果索引超出范围,则返回“No Answer”,或者如果反转的字符串等于原始字符串,则返回无答案。
代码
public class Main {
static ArrayList<String> arrayList = new ArrayList();
public static void main(String args[])
{
System.out.println(rearrangeWord("bacasadasdadasdzxczdasd"));
}
public static String rearrangeWord(String word) {
//Firstly we need to find and store all possible permutations in a lsit and then alphabetically sort our list
if(word.length() == 0)
{
return "no answer";
}
if(new StringBuilder(word).reverse().toString() == word)
{
return "no answer";
}
String sol = "";
permutation(word);
Collections.sort(arrayList);
for(int i = 0; i<arrayList.size(); ++i)
{
try{
if(arrayList.get(i).equals(word))
{
sol = arrayList.get(i+1);
}
}catch(IndexOutOfBoundsException e)
{
return "no answer";
}
}
return sol;
}
public static void permutation(String str) {
permutation("", str);
}
public static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) {arrayList.add(prefix);}
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
}
如何优化我的代码以处理更大的输入 2
【问题讨论】:
-
你的标题和你的问题描述很不一样。
标签: java string algorithm sorting recursion