题目:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:您可以假定该字符串只包含小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
解答:
用hashmap存字符串和对应位置,因为hashmap无序,就又用了list,重复的就把list里面的去掉,没有的就往list里面加,最后list里面留下来的第一个就是要的那个字符
class Solution { public int firstUniqChar(String s) { int res = -1; Map<String, String> map = new HashMap<String , String>(); List<String> list = new ArrayList<String>(); for (int i = 0; i < s.length(); i++) { String str = s.charAt(i) + ""; if (map.keySet().contains(str)) { list.remove(str); } else { map.put(str, i + ""); list.add(str); } } if (list.size() == 0) { res = -1; } else { String key = list.get(0); String intstr = map.get(key); res = Integer.parseInt(intstr); } return res; } }
嗯 果然 很慢~~
然后看到个简单粗暴的解法,直接判断首次和末次出现的位置,好酷~
class Solution { public int firstUniqChar(String s) { for(int i=0; i<s.length(); i++){ int first = s.indexOf(s.charAt(i)); int last = s.lastIndexOf(s.charAt(i)); if(first == last){ return i; } } return -1; } }