leetcode 387. First Unique Character in a String
LeetCode string in First unique character 387
2023-09-14 09:11:53 时间
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.
Note: You may assume the string contain only lowercase letters.
class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ cnt = collections.Counter(s) for i,c in enumerate(s): if cnt[c] == 1: return i return -1
java 里还可以,直接一次扫描s搞定:
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))) { if (map.get(s.charAt(i)) != null) { 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(); } }
因为map里entryset保存了add顺序???
相关文章
- leetcode 之Candy(12)
- Java实现 LeetCode 798 得分最高的最小轮调 (暴力分析)
- Java实现 LeetCode 438 找到字符串中所有字母异位词
- Java实现 Leetcode 169 求众数
- C#基础知识系列一(goto、i++、三元运算符、ref和out、String和string、重载运算符)
- 1,字符是否为空,2,比较两个字符大小。String.Compare(String, String)。string.IsNullOrEmpty(string)
- Kotlin 朱涛 实战 刷题 LeetCode
- LeetCode:149_Max Points on a line | 寻找一条直线上最多点的数量 | Hard
- 【RF库测试】Encode String To Bytes&Decode Bytes To String& should be string&should be unicode string &should not be string
- LeetCode-14. 最长公共前缀
- Leetcode学习计划之动态规划入门day13(931,120)
- 【LeetCode 30】串联所有单词的子串
- 【LeetCode 26】删除排序数组中的重复项
- LeetCode - 165 比较版本号
- LeetCode【8】. String to Integer (atoi) --java实现
- 【LeetCode Python实现】34. 在排序数组中查找元素的第一个和最后一个位置(中等)
- leetcode 24. 两两交换链表中的节点 js实现
- leetcode 1351. 统计有序矩阵中的负数 js实现
- LeetCode-Reverse Words in a String
- leetcode 342. Power of Four
- leetcode 344. Reverse String
- 【Mac系统】Vscode使用LeetCode插件报错‘leetcode.toggleLeetCodeCn‘ not found
- LeetCode 101. 对称二叉树