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

 

posted @ 2020-05-05 17:46  yawenw  阅读(120)  评论(0编辑  收藏  举报