简体   繁体   中英

How do I search for a word in an array of words with the same letters in a different order

the code below is working properly i just can't understand that part in the code

if (temp.indexOf(Search.charAt(j)) == -1){
    cpt=0;
} else {
    cpt++;
}

what does that condition mean ??

public static void main(String[] args) {
    String Search="loop";
    String[] words={"loop","pool","lopo","book","kobo","oopl","olop","opol"};
    int cpt=0;
    String temp;
    for(int i=0;i<words.length;i++){
        temp=words[i];
        for (int j=0 ; j<Search.length();j++) {
            if (temp.indexOf(Search.charAt(j))==-1){
                cpt=0;
            } else {
                cpt++;
            }
            if (cpt==4){
                System.out.println("-> :"+ temp);
                cpt=0;
            }
        }
    }
}

The idea of the code is to go through each word (call it temp ) in the list and compute how many characters in temp are present in Search .

For example "loop" and "pool" both have 1 'p', 1 'l' and 2 'p' characters.

But it's not completely correct...

This line if (temp.indexOf(Search.charAt(j))==-1) is checking to see if Search[j] exists in temp

but it should be more like

if(temp has this Search[j] character at some index (call it t) and t hasn't been used previously)

This should fail for cases like "loop" and "lop"
Also you're hardcoding the number 4 in the code, and it should be replaced by the length of Search

I recommend using a map.

As we know the index of method work on two condition .....

Condition 1 - if the giving character is exist in the string then it means the character is available at index 0 to string.lenth-1 index.

Condition 2 - if giving character is not exist in string that means the character is not available in that string from 0 index to entire string, so is return -1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM