Reduce your code by Lambdas/Stream APIs if you like


  • 0
    X
    public int firstUniqChar(String s) {
        Map<Integer, Integer> map = new LinkedHashMap<>();
        for (int i = 0, ch = 0, len = s.length(); i < len; i++) {
            ch = s.charAt(i);
            map.put(ch, map.containsKey(ch) ? Integer.MAX_VALUE : i);
        }
        // by forEach with index, above the for-loop can be simplified to: 
        // CharList.of(s.toCharArray()).forEach((i, ch) -> map.put(ch, map.containsKey(ch) ? Integer.MAX_VALUE : i));
    
        return map.entrySet().stream().filter(entry -> entry.getValue() != Integer.MAX_VALUE).map(entry -> entry.getValue()).findFirst().orElse(-1);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.