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

  • 相关阅读:
    ORA-14404
    ORA-00845
    ORA-00054
    oracle-11g-配置dataguard
    ORACLE 11G 配置DG 报ORA-10458、ORA-01152、ORA-01110
    Python:if __name__ == '__main__'
    HDFS-Shell 文件操作
    HDFS 概述
    PL/SQL Developer
    CentOS7 图形化方式安装 Oracle 18c 单实例
  • 原文地址:https://www.cnblogs.com/bonelee/p/8679027.html
Copyright © 2011-2022 走看看