First non repeating word in string.

public String firstNonRepeatingword(String string) {
        if(string == null || string.isEmpty()) {
            return "No unique word found";
        }else {
            StringTokenizer tokens = new StringTokenizer(string);
            LinkedList<String> list = new LinkedList<>();
            while(tokens.hasMoreTokens()) {
                list.add(tokens.nextToken());
            }
            for(int i=0;i<list.size();i++) {
                if (Collections.frequency(list,list.get(i)) == 1) {
                    return list.get(i);
                }
            }
        }
        return "No unique word found";
    }

It's up to you how are you spliting the string there are many ways, If you have small string tokenizer is fast.

Performance of StringTokenizer class vs. String.split method vs indexOf 

No comments:

Post a Comment

Functional programming with Java - Part 1

 Recently I was reviewing one PR raised by team memeber and going through one utitlity method and found out there are too many muatable vari...