387. First Unique Character in a String
Problem:
The idea is two pass. First pass count currency in map. Second path, find the first count == 1's char in map.
Solution:
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.Analysis:
The idea is two pass. First pass count currency in map. Second path, find the first count == 1's char in map.
Solution:
class Solution { public int firstUniqChar(String s) { if (s == null || s.length() == 0) return -1; int res = 0; Set<Character> checkSet = new HashSet<>(); Set<Character> dupSet = new HashSet<>(); for (char c: s.toCharArray()) { if (!checkSet.add(c)) { dupSet.add(c); } } for (int i = 0; i < s.length(); i++) { if (!dupSet.contains(s.charAt(i))) return i; } return -1; } }
评论
发表评论