死磕算法系列文章
“Leetcode : https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
“GitHub : https://github.com/nateshao/leetcode/blob/main/algo-notes/src/main/java/com/nateshao/sword_offer/topic_37_firstUniqChar/Solution.java
题目描述 :在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。s 只包含小写字母。
难度:简单
示例 1:
输入:s = "abaccdeff"
输出:'b'
示例 2:
输入:s = ""
输出:' '
s
,使用哈希表统计 “各字符数量是否 > 1 ”。s
,在哈希表中找到首个 “数量为 1 的字符”,并返回。算法流程:
dic
中不包含键(key)c:则向 dic
中添加键值对 (c, True)
,代表字符 c
的数量为1dic
中包含键(key) c
:则修改键 c
的键值对为 (c, False)
,代表字符 c
的数量>1s
中的每个字符 c
;dic
中键 c
对应的值为 True
:,则返回 c
。' '
,代表字符串无数量为 1 的字符。复杂度分析:
s
的长度;需遍历 s
两轮,使用 O(N) ;HashMap 查找操作的复杂度为 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 ' ';
}
}
参考链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/solution/mian-shi-ti-50-di-yi-ge-zhi-chu-xian-yi-ci-de-zi-3/