387. First Unique Character in a String
387. First Unique Character in a String public class Solution{ public int firstUniqChar(String s){ HashMap<Character, Integer> map = new HashMap<>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); Integer count = map.get(c); if(count == null){ map.put(c, 1); }else{ map.put(c, count + 1); } } for(int i = 0; i < s.length(); i++){ if(map.get(s.charAt(i)) == 1){ return i; } } return -1; } }
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.
posted on 2018-08-09 17:30 猪猪🐷 阅读(82) 评论(0) 收藏 举报
浙公网安备 33010602011771号