使用集合进行字符串去重 题目:给定一个字符串 Plain Texts = "aabbccddeeff" ,编写一个函数去除字符串中的重复字符,并返回结果字符串。
时间: 2024-11-27 15:11:24 浏览: 31
要使用集合(Set)来实现字符串去重,可以按照以下步骤操作:
1. 首先创建一个空的HashSet或HashMap,它们不允许有重复元素,因为集合内部会自动过滤掉重复项。
2. 遍历输入字符串,将每个字符逐个添加到集合中。由于哈希表(如HashMap)的特点,插入过程中如果遇到已经存在的键(对于字符而言即字符本身),则不会增加计数。
3. 最后,集合中的元素就是无重复的字符。转换回字符串即可。
下面是使用Java的示例代码:
```java
import java.util.HashSet;
public class StringRemoveDuplicates {
public static String removeDuplicates(String texts) {
HashSet<Character> uniqueChars = new HashSet<>();
StringBuilder result = new StringBuilder();
for (char c : texts.toCharArray()) {
if (!uniqueChars.contains(c)) {
result.append(c);
uniqueChars.add(c);
}
}
return result.toString();
}
public static void main(String[] args) {
String inputs = "aabbccddeeff";
System.out.println(removeDuplicates(inputs)); // 输出:"abcdef"
}
}
```
阅读全文
相关推荐


















