题目描述:

解题思路:
使用Java的HashMap集合框架,HashMap无重复值,将字符串2的每一个字符存入其中,然后遍历字符串1的每一个字符,判断map中是否存在该值,如果不存在则拼接到新的字符串中,如果存在则不进行拼接。
代码:
import java.util.*;
public class Main{
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
String str1 = scan.nextLine();
String str2 = scan.nextLine();
HashMap<Character,Integer> map = new HashMap<> ();
for(int i=0; i< str2.length() ;i++){
if( map.get( str2.charAt(i))== null){
map.put(str2.charAt(i),1);
}else{
map.put(str2.charAt(i),map.get(str2.charAt(i))+1);
}
}
String result="";
for(int i=0; i< str1.length() ; i++){
if(map.get(str1.charAt(i))==null){
result+=str1.charAt(i);
}
}
System.out.println(result);
}
}
该博客介绍了一种利用Java HashMap数据结构来去除字符串中重复字符的方法。通过遍历字符串2将字符存入HashMap,然后遍历字符串1并检查字符是否在HashMap中,不在的话则添加到结果字符串中,最终输出不含重复字符的新字符串。
3338

被折叠的 条评论
为什么被折叠?



