我正在尝试这个问题:
使用递归编写一个函数来显示用户输入的字符串的所有字谜词,使其所有元音都位于每个字谜词的末尾。 (例如:递归 => Rcrsneuio、cRsnroieu 等)对其进行优化。
从这个网站: http://erwnerve.tripod.com/prog/recursion/magic.htm
这就是我所做的:
public static void permute(char[] pre,char[] suff) {
if (isEmpty(suff)) {
//result is a set of string. toString() method will return String representation of the array.
result.add(toString(moveVowelstoEnd(pre)));
return;
}
int sufflen = getLength(suff); //gets the length of the array
for(int i =0;i<sufflen;i++) {
char[] tempPre = pre.clone();
char[] tempSuf = suff.clone();
int nextindex = getNextIndex(pre); //find the next empty spot in the prefix array
tempPre[nextindex] = tempSuf[i];
tempSuf = removeElement(i,tempSuf); //removes the element at i and shifts array to the left
permute(tempPre,tempSuf);
}
}
public static char[] moveVowelstoEnd(char[] input) {
int c = 0;
for(int i =0;i<input.length;i++) {
if(c>=input.length)
break;
char ch = input[i];
if (vowels.contains(ch+"")) {
c++;
int j = i;
for(;j<input.length-1;j++)
input[j] = input[j+1];
input[j]=ch;
i--;
}
}
return input;
}
问题的最后一部分是“优化它”。我不知道如何优化这个。有人可以帮忙吗?
最佳答案
将所有元音分组为 v
将所有辅音分组为 w
对于每对字谜,连接结果
关于java - 查找元音始终位于末尾的 Anagrams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16306965/