
在深入探讨查找唯一字符的逻辑之前,我们首先需要理解 Java String 类中两个核心方法的使用:charAt() 和 indexOf()。
charAt(int index) 方法用于返回字符串中指定索引位置的字符。
indexOf() 方法用于查找字符或子字符串在字符串中首次出现的位置。它有多种重载形式,其中两种对我们查找唯一字符至关重要:
indexOf(char ch):
indexOf(char ch, int fromIndex):
现在,我们来解析如何利用上述方法组合判断一个字符是否在字符串中是唯一的。核心判断条件是: s.indexOf(s.charAt(i), s.indexOf(s.charAt(i)) + 1) == -1
为了更好地理解这个表达式,我们将其分解:
下面是根据上述逻辑实现的 Java 代码,用于查找字符串中第一个唯一的字符的索引:
public class UniqueCharacterFinder {
/**
* 查找字符串中第一个不重复字符的索引。
* 如果所有字符都重复,则返回 -1。
*
* @param s 输入字符串
* @return 第一个不重复字符的索引,如果不存在则返回 -1
*/
public static int findFirstUniqueCharIndex(String s) {
// 遍历字符串中的每一个字符
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i); // 获取当前字符
// 查找当前字符在字符串中首次出现的位置
int firstOccurrenceIndex = s.indexOf(currentChar);
// 从首次出现位置的下一个索引开始,再次查找当前字符
// 如果从这个位置开始找不到该字符(即返回 -1),则说明它是唯一的
if (s.indexOf(currentChar, firstOccurrenceIndex + 1) == -1) {
return i; // 返回当前唯一字符的索引
}
}
return -1; // 如果循环结束都没有找到唯一字符,则返回 -1
}
public static void main(String[] args) {
String testString1 = "leetcode";
System.out.println("字符串 \"" + testString1 + "\" 中第一个唯一字符的索引是: " + findFirstUniqueCharIndex(testString1)); // 预期输出: 0 (l)
String testString2 = "loveleetcode";
System.out.println("字符串 \"" + testString2 + "\" 中第一个唯一字符的索引是: " + findFirstUniqueCharIndex(testString2)); // 预期输出: 2 (v)
String testString3 = "aabb";
System.out.println("字符串 \"" + testString3 + "\" 中第一个唯一字符的索引是: " + findFirstUniqueCharIndex(testString3)); // 预期输出: -1
}
}让我们逐步跟踪 findFirstUniqueCharIndex("leetcode") 的执行过程:
因此,对于 "leetcode",函数会立即返回 0,因为 'l' 是第一个唯一的字符。
让我们再看一个例子:"loveleetcode"
i = 0, currentChar = 'l':
i = 1, currentChar = 'o':
i = 2, currentChar = 'v':
因此,对于 "loveleetcode",函数返回 2,因为 'v' 是第一个唯一的字符。
通过巧妙地组合使用 String 类的 charAt() 和 indexOf() 方法,我们可以实现查找字符串中第一个唯一字符的功能。核心在于利用 indexOf(char ch, int fromIndex) 方法从字符首次出现位置的下一个索引开始进行二次查找。如果二次查找返回 -1,则表明该字符是唯一的。尽管这种方法在简洁性上表现出色,但在处理极端长度的字符串时,应考虑其 O(N^2) 的时间复杂度,并根据实际需求权衡是否采用更高效的基于哈希表的解决方案。
以上就是使用 indexOf 方法查找字符串中第一个唯一字符的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号