diff --git a/notes/剑指 offer 题解.md b/notes/剑指 offer 题解.md index b367d103..c4532c57 100644 --- a/notes/剑指 offer 题解.md +++ b/notes/剑指 offer 题解.md @@ -2027,6 +2027,8 @@ public int GetUglyNumber_Solution(int N) { ## 解题思路 +最直观的解法是使用 HashMap 对出现次数进行统计,但是考虑到要统计的字符范围有限,因此可以使用整型数组代替 HashMap。 + ```java public int FirstNotRepeatingChar(String str) { int[] cnts = new int[256]; @@ -2036,6 +2038,30 @@ public int FirstNotRepeatingChar(String str) { } ``` +以上的空间复杂度还不是最优的。考虑到最需要找到只出现一次的字符,那么我们只需要统计的次数信息只有 0,1,更大,那么使用两个比特位就能存储这些信息。 + +```java +public int FirstNotRepeatingChar(String str) { + BitSet bs1 = new BitSet(256); + BitSet bs2 = new BitSet(256); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (!bs1.get(c) && !bs2.get(c)) { // 0 0 + bs1.set(c); + } else if (bs1.get(c) && !bs2.get(c)) { // 0 1 + bs2.set(c); + } + } + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (bs1.get(c) && !bs2.get(c)) { + return i; + } + } + return -1; +} +``` + # 51. 数组中的逆序对 ## 题目描述