剑指 Offer 50. 第一个只出现一次的字符

116 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第3天,点击查看活动详情

Leetcode : leetcode-cn.com/problems/di…

GitHub : github.com/nateshao/le…

剑指 Offer 50. 第一个只出现一次的字符

题目描述 :在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。

难度:简单

示例 1:

 输入:s = "abaccdeff"
 输出:'b'

示例 2:

 输入:s = "" 
 输出:' '

这题不是很难,可以用暴力遍历,哈希都可以 还可以转换成数字

public char firstUniqChar(String s) {
        if (s.equals("")) return ' ';
        //创建‘a'-'z'的字典
        int[] target = new int[26];
        //第一次遍历,将字符统计到字典数组
        for (int i = 0; i < s.length(); i++) target[s.charAt(i) - 'a']++;
        //第二次遍历,从字典数组获取次数
        for (int i = 0; i < s.length(); i++) {
            if (target[s.charAt(i) - 'a'] == 1) return s.charAt(i);
        }
        return ' ';
    }

image.png

Go解法

func firstUniqChar(s string) byte {
    var res [26]int
    for i:=0;i<len(s);i++{
        res[s[i]-'a']++ 
    }
    for i:=0;i<len(s);i++{
    if res[s[i]-'a']==1{ //如果是写成res[i]==1,因为res前面的元素顺序对应为abcd,他们的值可能为1但是不一定是在s中第一个出现一次的字符
            return s[i]
        }
    }
    return ' '
} 

image.png

方法一:哈希表

  1. 遍历字符串 s ,使用哈希表统计 “各字符数量是否 > 1 ”。
  2. 再遍历字符串 s ,在哈希表中找到首个 “数量为 1 的字符”,并返回。

算法流程:

  1. 初始化:HashMap 记为dic ;

  2. 字符统计:遍历字符串s中的每个字符c ;

    1. dic 中不包含键(key)c:则向 dic 中添加键值对 (c, True) ,代表字符 c 的数量为1
    2. dic 中包含键(key) c :则修改键 c 的键值对为 (c, False) ,代表字符 c 的数量>1
  3. 查找数量为 1 的字符:遍历字符串 s 中的每个字符 c

    1. dic中键 c 对应的值为 True :,则返回 c
  4. 返回 ' ' ,代表字符串无数量为 1 的字符。

复杂度分析:

  • 时间复杂度 O(N) : N 为字符串 s 的长度;需遍历 s 两轮,使用 O(N) ;HashMap 查找操作的复杂度为 O(1) ;
  • 空间复杂度 O(1): 由于题目指出 s 只包含小写字母,因此最多有 26 个不同字符,HashMap 存储需占用 O(26) = O(1) 的额外空间。

方法二:有序哈希表

在哈希表的基础上,有序哈希表中的键值对是按照插入顺序排序的。基于此,可通过遍历有序哈希表,实现搜索首个“数量为1的字符”。

哈希表是去重的,即哈希表中键值对数量 ≤ 字符串s的长度。因此,相比于方法一,方法二减少了第二 轮遍历的循环次数。当字符串很长(重复字符很多)时,方法二则效率更高。

复杂度分析: 时间和空间复杂度均与“方法一” 相同,而具体分析:方法一需遍历s两轮;方法二遍历s - -轮,遍历dic一轮(dic的长度不大于26)。

 package com.nateshao.sword_offer.topic_37_firstUniqChar;
 ​
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
 ​
 /**
  * @date Created by 邵桐杰 on 2021/12/14 18:15
  * @微信公众号 千羽的编程时光
  * @个人网站 www.nateshao.cn
  * @博客 https://nateshao.gitee.io
  * @GitHub https://github.com/nateshao
  * @Gitee https://gitee.com/nateshao
  * Description:在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
  * 示例 1: 输入:s = "abaccdeff"   输出:'b'
  * https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/
  */
 public class Solution {
     public static void main(String[] args) {
         String s = "abaccdeff";
         String s2 = "";
         System.out.println("firstUniqChar(s) = " + firstUniqChar(s));//firstUniqChar(s) = b
         System.out.println("firstUniqChar(s2) = " + firstUniqChar(s2));
         System.out.println("firstUniqChar2(s) = " + firstUniqChar2(s));//firstUniqChar2(s) = b
     }
 ​
     /**
      * 利用 HashMap 和 LinkedHashMap(效率更高) 保存字符和出现次数。
      * @param s
      * @return
      */
     public static char firstUniqChar(String s) {
         if (s == null || s.length() == 0) return ' ';
         char[] chars = s.toCharArray();
         Map<Character, Boolean> hashMap = new HashMap<>();
 //        LinkedHashMap<Character, Boolean> linkedHashMap = new LinkedHashMap<>();
         for (char c : chars) {
             hashMap.put(c, !hashMap.containsKey(c));
         }
         for (char c : chars) {
             if (hashMap.get(c)) return c;
         }
         return ' ';
     }
 ​
     public static char firstUniqChar2(String s) {
         Map<Character, Boolean> dic = new LinkedHashMap<>();
         char[] sc = s.toCharArray();
         for(char c : sc)
             dic.put(c, !dic.containsKey(c));
         for(Map.Entry<Character, Boolean> d : dic.entrySet()){
             if(d.getValue()) return d.getKey();
         }
         return ' ';
     }
 ​
 }

参考链接:leetcode-cn.com/problems/di…

\