用Java写一个程序用来找出两个字符串中所有公共的字符
时间: 2023-09-17 16:09:47 浏览: 50
可以使用哈希表(HashMap)来实现,算法的步骤如下:
1. 首先,建立一个哈希表,将第一个字符串中的所有字符添加到哈希表中。
2. 然后,遍历第二个字符串中的所有字符,如果这个字符在哈希表中存在,那么就将它添加到结果集中,并将哈希表中对应的键值对删除。
3. 最后,返回结果集即可。
代码实现如下:
```java
import java.util.*;
public class CommonChars {
public static List<Character> findCommonChars(String s1, String s2) {
Map<Character, Integer> map = new HashMap<>();
List<Character> result = new ArrayList<>();
// 将 s1 中的字符添加到哈希表中
for (int i = 0; i < s1.length(); i++) {
char c = s1.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
// 遍历 s2 中的字符,如果存在于哈希表中,则添加到结果集中
// 并将哈希表中对应的键值对删除
for (int i = 0; i < s2.length(); i++) {
char c = s2.charAt(i);
if (map.containsKey(c)) {
result.add(c);
map.put(c, map.get(c) - 1);
if (map.get(c) == 0) {
map.remove(c);
}
}
}
return result;
}
public static void main(String[] args) {
String s1 = "abcdefg";
String s2 = "bcdghij";
List<Character> result = findCommonChars(s1, s2);
System.out.println(result);
}
}
```
以上程序输出结果为:`[b, c, d, g]`,即两个字符串中所有公共的字符。