From 3f5749209435c0c30a6e420eeddb60b76f2adcfa Mon Sep 17 00:00:00 2001 From: CyC2018 Date: Wed, 28 Oct 2026 13:45:06 +0800 Subject: [PATCH] =?UTF-8?q?Update=2050.=20=E7=AC=AC=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=8F=AA=E5=87=BA=E7=8E=B0=E4=B8=80=E6=AC=A1=E7=9A=84=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=BD=8D=E7=BD=AE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 题目链接改为力扣中的对应题目,按该题返回第一个只出现一次的字符。 --- notes/50. 第一个只出现一次的字符位置.md | 40 ++++++++++++++----------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/notes/50. 第一个只出现一次的字符位置.md b/notes/50. 第一个只出现一次的字符位置.md index 8f9cd0c8..b053f8e2 100644 --- a/notes/50. 第一个只出现一次的字符位置.md +++ b/notes/50. 第一个只出现一次的字符位置.md @@ -2,11 +2,11 @@ ## 题目链接 -[牛客网](https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=13&tqId=11187&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) +[Leetcode](https://leetcode.cn/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/) ## 题目描述 -在一个字符串中找到第一个只出现一次的字符,并返回它的位置。字符串只包含 ASCII 码字符。 +在一个字符串中找到第一个只出现一次的字符。若不存在则返回单空格。 ```text Input: abacc @@ -20,34 +20,38 @@ Output: b 考虑到要统计的字符范围有限,也可以使用整型数组代替 HashMap。ASCII 码只有 128 个字符,因此可以使用长度为 128 的整型数组来存储每个字符出现的次数。 ```java -public int FirstNotRepeatingChar(String str) { +public char dismantlingAction(String arr) { int[] cnts = new int[128]; - for (int i = 0; i < str.length(); i++) - cnts[str.charAt(i)]++; - for (int i = 0; i < str.length(); i++) - if (cnts[str.charAt(i)] == 1) - return i; - return -1; + for (int i = 0; i < arr.length(); i++) { + cnts[arr.charAt(i)]++; + } + for (int i = 0; i < arr.length(); i++) { + if (cnts[arr.charAt(i)] == 1) { + return arr.charAt(i); + } + } + return ' '; } ``` 以上实现的空间复杂度还不是最优的。考虑到只需要找到只出现一次的字符,那么需要统计的次数信息只有 0,1,更大,使用两个比特位就能存储这些信息。 ```java -public int FirstNotRepeatingChar2(String str) { +public char dismantlingAction(String arr) { BitSet bs1 = new BitSet(128); BitSet bs2 = new BitSet(128); - for (char c : str.toCharArray()) { - if (!bs1.get(c) && !bs2.get(c)) + for (char c : arr.toCharArray()) { + if (!bs1.get(c) && !bs2.get(c)) { bs1.set(c); // 0 0 -> 0 1 - else if (bs1.get(c) && !bs2.get(c)) + } else if (bs1.get(c) && !bs2.get(c)) { bs2.set(c); // 0 1 -> 1 1 + } } - for (int i = 0; i < str.length(); i++) { - char c = str.charAt(i); - if (bs1.get(c) && !bs2.get(c)) // 0 1 - return i; + for (char c : arr.toCharArray()) { + if (bs1.get(c) && !bs2.get(c)) { // 0 1 + return c; + } } - return -1; + return ' '; } ```