有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

}

共 (3) 个答案

  1. # 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字母

    Word[] = {'h','e','l','l','o'}
    indexes =  0 , 1 , 2 , 3 , 4
    
    
    index[]= { 0 , 2 ,3}  //Store the indexes of characters which are to be changed
    
    
    BITSET      |       SUBSET      |       word
    
    000         |         -         |       hello 
    001         |        {3}        |       helLo 
    010         |        {2}        |       heLlo 
    011         |       {2,3}       |       heLLo 
    100         |        {0}        |       Hello 
    101         |       {0,3}       |       HelLo 
    110         |       {0,2}       |       HeLlo 
    111         |      {0,2,3}      |       HeLLo 
    

    代码:

    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<Integer> test1 = lettersFound(word, rule_char_set); //To store the indexes of the characters
    
            printPermutations(word,test1);
    
        }
    
        public static void printPermutations(String word,ArrayList<Integer> arrayList) {
            char word_array[]=word.toLowerCase().toCharArray();
            int length=word_array.length;
            int index[]=new int[arrayList.size()];
    
            for(int i=0; i<arrayList.size(); i++){
                index[i] = arrayList.get(i);
            }
    
            for (int i = 0, n = (int) Math.pow(2, index.length); i < n; i++) {
                char[] permutation = new char[length];
    
                System.arraycopy(word_array,0,permutation,0,length);    
    
                //First copy the original array and change 
                //only those character whose indexes are present in subset
    
                for (int j =0; j < index.length; j++) {
                    permutation[index[j]] = (isBitSet(i, j)) ? Character.toUpperCase(permutation[index[j]]) : permutation[index[j]];
                }
                System.out.println(permutation);
            }
        }
    
        public static boolean isBitSet(int n, int offset) {
            return (n >> offset & 1) != 0;
        }
    
        public static ArrayList<Integer> 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<Integer> found = new ArrayList<Integer>();
    
            //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, k);       //Store the index of the character that matches
                        foundCounter++;
    
                    }
                }
            }
            return found;
        }
    
    }
    

    输出:

    tomorrow-today
    Tomorrow-today
    tomorrow-Today
    Tomorrow-Today
    tomorroW-today
    TomorroW-today
    tomorroW-Today
    TomorroW-Today
    
  2. # 2 楼答案

    Sanket Makani的答案是完美的

    我可以提供一个更客观的方法来解决这个问题

    作为输入,您需要修改字符串和字符,这些字符应替换为已修改的大小写(大写或小写)。 作为输出,您将拥有所有置换字符串

    我将创建一个包含索引的结构,以及可能随以下内容而更改的值:

    class Change {
    int index;
    char values[];
    }
    

    我们将需要进行所有可能的组合,因此让我们包括一个字段,该字段将告诉我们的结构中当前使用的字符,并添加一些方法:

    class Change {
    int index;
    char values[];
    int cur;
    
    void reset() {cur=0;}
    boolen isMax(){return cur==values.length-1;}
    void next(){cur++;}
    char getValue(){ return values[cur]; }
    } 
    

    我们将有一个这些类的列表或数组,我们将把它们放入一个单独的类中

    class Combination {
    Change changes[];
    
      void reset() { for (Change c: changes) c.reset();}
    
      boolean next() {
       for ( int i=0; i<changes.length; i++)
          if ( changes[i].isMax())
             changes[i].reset(); // next change will be taken in cycle, with "next()"
          else {changes[i].next(); return true;}
    
       return false; // all changes are max
      }
    }
    

    所以,当您通过输入数据初始化“组合”类时,您可以在循环中使用它

    Combination c = new Combination();
    .... // initialization here 
    c.reset();
    do {
     ... //  update and print your string
    } while ( c.next()  );
    

    初始化“组合”并使用值更新我在您之后留下的输入字符串:)

  3. # 3 楼答案

    对于置换的情况,我认为递归在可读性方面是最合适的,考虑到它在性能方面可能不是最好的

    我的做法是:

    public static void main(String[] args) {
        generateCombinations("hello", "l", "");
    }
    
    public static void generateCombinations(String text, String changingLetters, String current) {
        if (0 == text.length()) {
            System.out.println(current);
            return;
        }
        String currentLetter = text.substring(0, 1);
        if (changingLetters.contains(currentLetter)) {
            generateCombinations(text.substring(1), changingLetters, current + currentLetter.toUpperCase());
        }
        generateCombinations(text.substring(1), changingLetters, current + currentLetter);
    }
    

    主执行的输出将是:

    heLLo
    heLlo
    helLo
    hello