JAVA中字符数组中的特定元素排列?
如何列出字符数组中指定的任何字母的所有大小写排列? 假设我有一个这样的字符数组:['h','e','l','l','o'] 我想打印出字母“l”的可能组合,这样它就能打印出来[你好,你好,你好,你好]
这就是我到目前为止所拥有的(唯一的问题是我可以打印排列,但是我无法在实际单词中打印它们。因此我的代码打印[ll,ll,ll,ll],而不是上面的示例
我的代码:
import java.util.ArrayList;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
//Sample Word
String word = "Tomorrow-Today";
//Sample Letters for permutation
String rule_char_set = "tw";
ArrayList<Character> test1 = lettersFound(word, rule_char_set);
printPermutations(test1);
}
public static void printPermutations(ArrayList<Character> arrayList) {
char[] chars = new char[arrayList.size()];
int charIterator = 0;
for(int i=0; i<arrayList.size(); i++){
chars[i] = arrayList.get(i);
}
for (int i = 0, n = (int) Math.pow(2, chars.length); i < n; i++) {
char[] permutation = new char[chars.length];
for (int j =0; j < chars.length; j++) {
permutation[j] = (isBitSet(i, j)) ? Character.toUpperCase(chars[j]) : chars[j];
}
System.out.println(permutation);
}
}
public static boolean isBitSet(int n, int offset) {
return (n >> offset & 1) != 0;
}
public static ArrayList<Character> lettersFound(String word, String rule_char_set) {
//Convert the two parameter strings to two character arrays
char[] wordArray = word.toLowerCase().toCharArray();
char[] rule_char_setArray = rule_char_set.toLowerCase().toCharArray();
//ArrayList to hold found characters;
ArrayList<Character> found = new ArrayList<Character>();
//Increments the found ArrayList that stores the existent values.
int foundCounter = 0;
for (int i = 0; i < rule_char_setArray.length; i++) {
for (int k = 0; k < wordArray.length; k++) {
if (rule_char_setArray[i] == wordArray[k]) {
found.add(foundCounter, rule_char_setArray[i]);
foundCounter++;
}
}
}
//Convert to a HashSet to get rid of duplicates
HashSet<Character> uniqueSet = new HashSet<>(found);
//Convert back to an ArrayList(to be returned) after filtration of duplicates.
ArrayList<Character> filtered = new ArrayList<>(uniqueSet);
return filtered;
}
}
# 1 楼答案
您需要在程序中做一些更改。您的逻辑是完美的,您需要首先找到给定单词中要更改的
characters
。找到它们后,查找characters
中的powerset
以打印所有排列,但这将只打印给定单词中存在的rule-char-set
字符中的permuatation
您需要做的一些更改是,首先查找
word
中包含rule-char-set
字符的所有indexes
。然后找到存储在ArrayList
中的所有subsets
索引,然后对于每个子集的每个元素,使character
出现在index
的大写字母上,这将提供您所需的所有permutation
考虑一个例子,{{CD14>}和^ {CD15>},然后首先需要在字符串{{CD7}}中找到所有索引^ {CD16>}和^ {CD17>}。
所以这里的索引是
0,2,3
。将其存储在ArrayList
中,然后查找其powerset
。然后,对于每个subset
,使character
出现在index
上的uppercase
字母代码:
输出:
# 2 楼答案
Sanket Makani的答案是完美的
我可以提供一个更客观的方法来解决这个问题
作为输入,您需要修改字符串和字符,这些字符应替换为已修改的大小写(大写或小写)。 作为输出,您将拥有所有置换字符串
我将创建一个包含索引的结构,以及可能随以下内容而更改的值:
我们将需要进行所有可能的组合,因此让我们包括一个字段,该字段将告诉我们的结构中当前使用的字符,并添加一些方法:
我们将有一个这些类的列表或数组,我们将把它们放入一个单独的类中
所以,当您通过输入数据初始化“组合”类时,您可以在循环中使用它
初始化“组合”并使用值更新我在您之后留下的输入字符串:)
# 3 楼答案
对于置换的情况,我认为递归在可读性方面是最合适的,考虑到它在性能方面可能不是最好的
我的做法是:
主执行的输出将是: