Home > Blockchain >  Find the first Recurring letter in Java
Find the first Recurring letter in Java

Time:05-23

I wrote the code as follows but it doesn't return the first recurring letter properly.

Example:

In the word "statistics" the recurring letters are s, t, and i. But the letter t recurs sooner than the letter s and i, but my program returns s instead of t.

What do I need to do for it to return t, using two for loops, as per the task in hand?

public class Main {
    public static char FRL(String word){
        for(int i = 0; i<word.length(); i  ){
            for(int j = i 1; j<word.length(); j  ){
                if(word.charAt(i) == word.charAt(j)){
                    return word.charAt(i);
                }
            }
        }
        return '0';
    }

    public static void main(String[] args) {
        String word = "statistics";
        if (FRL(word) != '0'){
            System.out.println(FRL(word));
        }else{
            System.out.println("No reccurring letter!");
        }
    }
}

CodePudding user response:

You can reduce eliminate the nested loop and improve the performance by storing every encountered character in a HashSet:

public static char FRL(String word){
    Set<Character> seen = new HashSet<>();
    for(int i = 0; i < word.length(); i  ) {
        char next = word.charAt(i);
        if (!seen.add(next)) {
            return next;
        }
    }
    return '0';
}

But if you have a requirement to use a nested loop, then you should fix the initialization expression and condition of the inner for loop, i.e. we should be check characters starting from index 0 inclusive and up to index i exclusive:

public static char FRL(String word) {
    for(int i = 0; i < word.length(); i  ) {
        char next = word.charAt(i);
        for(int j = 0; j < i; j  ){
            if(next == word.charAt(j)) {
                return next;
            }
        }
    }
    return '0';
}

By the way, getFirstRecuringLetter() would be a better method name than FRL.

  • Related