gpt4 book ai didi

java - 在字符数组java中查找一个单词

转载 作者:行者123 更新时间:2023-11-30 02:04:44 25 4
gpt4 key购买 nike

我正在尝试从 dictonary list 中查找单词。字母可以按任何顺序排列,但任何字母只能使用一次。我已经在Android上用java开发了一种算法,但它并没有真正起作用。--> 在我的原因中,字典列表中的所有单词都已小写

这是我现有的代码,但它不会显示匹配的单词作为输出,返回的列表始终为空。

    private int matches = 0;
private ArrayList<String> words;

private ArrayList<String> check(String charArr0) {
String charArr = charArr0.toLowerCase();
char[] cs0 = charArr.toCharArray();
ArrayList<Character> cs = new ArrayList<>();
for(char c : cs0)
cs.add(c);
all = words.size();
ArrayList<String> out = new ArrayList<>();

for(String w0 : words) {
String w = w0.toLowerCase();
int len = w.length();
if(len >= 2) {
//only if len is 2++
matches = 0;
checkNext(cs, 0, w, len);
//if matches are as high as words lenght, it is fully avaivable
if(matches >= len)
out.add(w);
}
}

return out;
}

private void checkNext(ArrayList<Character> cs, int pos, String w, int len) {
if(pos < len) {
char twc = w.charAt(pos);
boolean cont = false;
int cIdx = -1, curi = 0;
for(char c : cs) {
if(c == twc){
cont = true;
cIdx = curi;
break;
}

curi += 1;
}

if(cont) {
matches += 1;
cs.remove(cIdx);
checkNext(cs, pos + 1, w, len);
}
}
}

问题是,这段代码中的错误是什么,我如何从给定的 char 数组中的列表中获取单词(任何 char 只使用一次,顺序无关紧要)?

最佳答案

因为你定义了这个规则:

//- The letters can be in any order
//- any letter can be used only once

我想对每个单词的字符进行排序并检查它们是否相等:

List<String> dictionaryWords = ...;
String word = "word";
char[] wordChars = word.toCharArray();
Arrays.sort(wordChars);
List<String> foundWords = new ArrayList<>();
for(String w : dictionaryWords){
if(dictionaryWords.length() != wordChars.length)
continue;
char[] wordDictionaryChars = w.toCharArray();
Arrays.sort(wordDictionaryChars);
if(Arrays.equals(wordChars, wordDictionaryChars)){
foundWords.add(w);
}
}

假设你有:

List<String> dictionaryWords = new ArrayList<>(Arrays.asList("drow", "hello"));

这将返回:

[drow]

因为当您同时订购 worddrow 时,它会给您[d, o, r, w]

关于java - 在字符数组java中查找一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51693558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com