剑指Offer:第一个只出现一次的字符Java/Python

1.题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

2.算法描述

1.以字符为键,字符出现的次数为值建立hash表,遍历一遍字符串,统计每个字符出现的次数。
2.遍历字符串,根据hash表的值得知是否存在出现次数为1的字符或者如果存在返回其位置。

3.代码描述

3.1.Java代码

import java.util.*;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        Map<Character, Integer> map = new HashMap<>();
        for(char c: str.toCharArray()){
            map.put(c, 1 + map.getOrDefault(c, 0));
        }
        for(int i = 0; i< str.length(); i++){
            if(map.get(str.charAt(i)) == 1)
                return i;
        }
        return -1;
    }
}

3.2.Python代码

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        maps = {}
        for c in s:
            maps[c] = maps.get(c,0) + 1
        for i,c in enumerate(s):
            if maps.get(c)== 1:
                return i
        return -1

猜你喜欢

转载自blog.csdn.net/qq_37888254/article/details/89839509