【牛客网OJ题】删除公共字符

问题描述:

输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。

例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”

分析:

有三种办法(我知道的就三种):

1. 利用map集合,将要删除的字符串的存进map中,遍历原来的字符串,如果字符串中的字符在map中有,那么就进行下一次循环,否则就直接打印。

import java.util.*;
public class Main{
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String str = sc.nextLine();
            String s = sc.nextLine();
            int index = 0;
            Map<Integer,Character> map = new TreeMap<>();
            for(int i = 0;i<s.length();i++){
                map.put(index,s.charAt(i));
                index++;
            }
            for(int i = 0;i<str.length();i++){
                if(!map.containsValue(str.charAt(i))){
                    System.out.println(str.charAt(i));
                }
            }
           
        }
    }

2.用replaceAll替换,replaceAll方法传入的第一个参数是正则表达式,字符串形式的正则表达式是[abcd...]。


import java.util.Scanner;
public class Main {
    public static void main(String[] args)  {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s1 = sc.nextLine();
            String s2 = sc.nextLine();
            String pattern = "[" + s2 + "]";
            String result = s1.replaceAll(pattern, "");
            System.out.println(result);
        }
    }
}

3.下面将“They are students.”称为字符串1,将“aeiou”称为字符串2。每遍 历到字符串2中的一个字符,就在字符串1中找到相同的字符,找到之后删除它,并将字符串1后面的字符整 体向前移动1位。

import java.util.Scanner;

public class Main{
	public static void main(String[] args){

	    Scanner sc = new Scanner(System.in);
	    while(sc.hasNext()){
		    char[] ch = sc.nextLine().toCharArray();
		    String str = sc.nextLine();
		    for(int i=0;i<ch.length;i++){
			    if(!str.contains(String.valueOf(ch[i]))){
				System.out.print(ch[i]);
			   }
		    }
	    }
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值