zoukankan      html  css  js  c++  java
  • leetcode 387. First Unique Character in a String

    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顺序???

  • 相关阅读:
    mysql 优化
    对象的特征
    对象的回收机制
    对象产生的过程
    python 内容查询小助手
    python笔记
    python安装MySQLdb模块
    python笔记
    python笔记
    定期删除备份文件,节省磁盘空间脚本
  • 原文地址:https://www.cnblogs.com/bonelee/p/8679027.html
Copyright © 2011-2022 走看看