美文网首页皮皮的LeetCode刷题库
【剑指Offer】034——第一个只出现一次的字符(字符串)

【剑指Offer】034——第一个只出现一次的字符(字符串)

作者: 就问皮不皮 | 来源:发表于2019-08-20 12:45 被阅读0次

题目描述

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

解题思路

先在hash表中统计各字母出现次数,第二次扫描直接访问hash表获得次数。也可以用数组代替hash表。

参考代码

import java.util.HashMap;
public class Solution {
    // HashMap方法
    public int FirstNotRepeatingChar(String str) {
        int len = str.length();
        if(len == 0) return -1;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            if (map.containsKey(str.charAt(i))){
                int value = map.get(str.charAt(i));
                map.put(str.charAt(i), value + 1);
            }else{
                map.put(str.charAt(i), 1);
            }
        }
        for (int i = 0; i < len; i++) {
            if (map.get(str.charAt(i)) == 1){
                return i;
            }
        }
        return -1;
    }
    // 数组方法
    public int FirstNotRepeatingChar2(String str) {
        int len = str.length();
        if(len == 0) return -1;
        char[] s = str.toCharArray();
        int[] m = new int[256];  // 用字符的整数存储
        // 类似于桶,一个萝卜一个坑
        for (int i = 0; i < len; i++) {
            m[s[i]]++;
        }
        for (int i = 0; i < len; i++) {
            if (m[s[i]] == 1){
                return  i;
            }
        }
        return -1;
    }
}

Python

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        dic = {}
        for i in range(len(s)):
            if s[i] not in dic.keys():
                dic[s[i]] = 1
            else:
                dic[s[i]] = dic[s[i]] + 1
        for i in range(len(s)):
            if dic[s[i]] == 1:
                return i
        return -1

个人订阅号

image

相关文章

网友评论

    本文标题:【剑指Offer】034——第一个只出现一次的字符(字符串)

    本文链接:https://www.haomeiwen.com/subject/iuzusctx.html