zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge5 之 字符转ASCII码

    Python知识点:

    ord() 字符转ASCII码,chr() ASCII码转字符。

    count = collections.Counter(s)  Counte可以理解为一个计数器,可以传入一个list或者string。返回一个({:})。其中.most common(2) 表示出现次数最高的前两个。

    enumerate()是枚举,可以在循环中枚举数组中的下标和值。

    JAVA知识点:

    map.put(c, getOrDefault(c, 0)+1)

    本题提供两种解法:

    1.利用字符的ASCII码连续性,巧妙的运用(char - 'a'),将字符出现的次数存储在size为26的数组中。然后遍历字符串,如果数组中次数为1,则返回下标。

    2.利用HashMap统计字符及出现的次数。然后遍历字符串,如果数组中次数为1,则返回下标。此解法容易想到。

    JAVA

    class Solution {
        public int firstUniqChar(String s) {
            int[] times = new int[26];
            for(int i = 0; i < s.length(); i++){
                times[s.charAt(i) - 'a'] ++;
            }
            for(int j = 0; j < s.length(); j++){
                if(times[s.charAt(j) - 'a'] == 1) return j;
            }
            return -1;
        }
    }
    class Solution {
        public int firstUniqChar(String s) {
            Map<Character, Integer> map = new HashMap<>();
            for(int i = 0; i < s.length(); i++){
                char c = s.charAt(i);
                map.put(c, map.getOrDefault(c, 0)+1);
            }
            for(int j = 0; j < s.length(); j++){
                if(map.get(s.charAt(j)) == 1) return j;
            }
            return -1;
        }
    }

    Python3

    class Solution:
        def firstUniqChar(self, s: str) -> int:
            times = [0]*26
            for i in range(len(s)):
                times[ord(s[i])-ord('a')] += 1 #ord()实现字符转ASCII码 chr()反之
            for j in range(len(s)):
                if times[ord(s[j])-ord('a')] == 1:
                    return j
            return -1
    class Solution:
        def firstUniqChar(self, s: str) -> int:
            count = collections.Counter(s)
            for index, char in enumerate(s):
                if count[char] == 1:
                    return index
            return -1
  • 相关阅读:
    vue 路由的实现 hash模式 和 history模式
    标准规范
    知识产权、项目收尾
    合同法、著作权、实施条例
    招投标法、政府采购法
    项目成熟度模型、量化项目管理
    信息系统综合测试与管理
    信息系统安全管理
    Spring Boot 6. 与数据访问
    Spring Boot 5. 与Docker
  • 原文地址:https://www.cnblogs.com/yawenw/p/12831603.html
Copyright © 2011-2022 走看看