14. 如何在字符串中查找重复字符或子字符串?
大约 2 分钟
在Java中,查找字符串中的重复字符或子字符串可以通过多种方式实现。下面是一些常见的方法:
1. 查找重复字符
要查找字符串中出现多次的字符,可以使用HashMap
来统计每个字符的出现次数,并找出那些出现次数大于1的字符。
示例代码
import java.util.HashMap;
import java.util.Map;
public class DuplicateCharFinder {
public static void main(String[] args) {
String text = "programming";
Map<Character, Integer> charCountMap = new HashMap<>();
// 统计每个字符的出现次数
for (char c : text.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// 找出出现多次的字符
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println("Character '" + entry.getKey() + "' occurs " + entry.getValue() + " times.");
}
}
}
}
输出
Character 'r' occurs 2 times.
Character 'g' occurs 2 times.
Character 'm' occurs 2 times.
2. 查找重复子字符串
要查找字符串中重复出现的子字符串,可以使用嵌套循环结合substring()
方法来截取和比较字符串的各个子串。也可以使用HashMap
或HashSet
来存储和检查子字符串。
示例代码
import java.util.HashMap;
import java.util.Map;
public class DuplicateSubstringFinder {
public static void main(String[] args) {
String text = "abcabcabc";
int subStrLength = 3;
Map<String, Integer> subStrCountMap = new HashMap<>();
// 遍历所有可能的子字符串
for (int i = 0; i <= text.length() - subStrLength; i++) {
String subStr = text.substring(i, i + subStrLength);
subStrCountMap.put(subStr, subStrCountMap.getOrDefault(subStr, 0) + 1);
}
// 找出出现多次的子字符串
for (Map.Entry<String, Integer> entry : subStrCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println("Substring '" + entry.getKey() + "' occurs " + entry.getValue() + " times.");
}
}
}
}
输出
Substring 'abc' occurs 3 times.
3. 查找重复字符(使用Set
)
可以使用Set
来跟踪已经遇到的字符,并找出重复的字符。
示例代码
import java.util.HashSet;
import java.util.Set;
public class DuplicateCharFinderWithSet {
public static void main(String[] args) {
String text = "javaprogramming";
Set<Character> charsSeen = new HashSet<>();
Set<Character> duplicateChars = new HashSet<>();
// 遍历字符串找出重复字符
for (char c : text.toCharArray()) {
if (!charsSeen.add(c)) {
duplicateChars.add(c);
}
}
// 输出重复字符
System.out.println("Duplicate characters: " + duplicateChars);
}
}
输出
Duplicate characters: [a, r, g, m]
总结
- 查找重复字符: 使用
HashMap
统计字符频率,或使用Set
查找重复字符。 - 查找重复子字符串: 使用
HashMap
统计子字符串的出现次数,通过嵌套循环或滑动窗口遍历字符串。
根据具体的需求和应用场景,可以选择合适的方法来查找字符串中的重复字符或子字符串。这些方法可以帮助检测重复元素,并根据需要处理字符串中的重复信息。