387. First Unique Character in a String
Easy
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode" return 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public int firstUniqChar(String s) { Map<Character, Integer> map = new LinkedHashMap<>(); Set<Character> set = new HashSet<>(); for (int i = 0; i < s.length(); i++) { if (set.contains(s.charAt(i))) { map.remove(s.charAt(i)); } else { map.put(s.charAt(i), i); set.add(s.charAt(i)); } } return map.size() == 0 ? -1 : map.entrySet().iterator().next().getValue(); } } |
No comments:
Post a Comment