在java字符数组中查找单词
我在试着从一个词中找到一个词。字母可以按任何顺序排列,但任何字母只能使用一次。我已经在Android上用java开发了一个算法,但它并没有真正起作用。 -->在我的原因中,dict列表中的所有单词都已小写 这是我现有的代码,但它不会显示匹配的单词作为输出,返回的列表总是空的在java字符数组中查找单词,java,char,Java,Char,我在试着从一个词中找到一个词。字母可以按任何顺序排列,但任何字母只能使用一次。我已经在Android上用java开发了一个算法,但它并没有真正起作用。 -->在我的原因中,dict列表中的所有单词都已小写 这是我现有的代码,但它不会显示匹配的单词作为输出,返回的列表总是空的 private int matches = 0; private ArrayList<String> words; private ArrayList<String> che
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);
}
}
}
private int matches=0;
私人ArrayList词;
专用ArrayList检查(字符串字符0){
字符串charArr=charArr0.toLowerCase();
char[]cs0=charArr.toCharArray();
ArrayList cs=新的ArrayList();
用于(字符c:cs0)
cs.添加(c);
all=words.size();
ArrayList out=新的ArrayList();
for(字符串w0:单词){
字符串w=w0.toLowerCase();
int len=w.length();
如果(len>=2){
//只要len是2++
匹配=0;
检查下一步(cs,0,w,len);
//如果匹配的长度与单词长度一样高,则完全可用
如果(匹配>=len)
加上(w);
}
}
返回;
}
私有void checkNext(ArrayList cs,int pos,String w,int len){
如果(位置
问题是,这段代码中的错误是什么?我如何可能从给定字符数组的列表中获取一个单词(任何字符只使用一次,顺序无关紧要)?因为您定义了以下规则:
//- 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);
}
}
因为当您同时订购word和drow时,它将为您提供
[d,o,r,w]
问题是什么?我更新了问题@Malt@Malt我只是想有人改进代码,或者给我一个关于如何实现这一点的另一种方法的建议谢谢你@Shivangagarwal我们还可以通过为每个长度提供单独的列表来提高其性能,并将它们保留在地图上,这有助于减少for循环周期。也可以考虑使用一个已经排序的列表来忽略排序操作。如果“drow”包含的字符多于这4个,怎么办?ShivangAgarwal我同意你的观点,我认为这也取决于用户,在他的情况下,我会为每个单词存储一个排序的单词,可以在search@Deplover“卓尔”是什么意思是否包含超过这4个字符?是否要接受与您的单词长度不同的单词?
List<String> dictionaryWords = new ArrayList<>(Arrays.asList("drow", "hello"));
[drow]