算法题——确定两串乱序同构

本文探讨了如何通过编程判断两个字符串是否可以通过字符排列转换成为彼此。重点在于大小写区分和考虑空格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

欢迎转载,请附出处:
http://blog.csdn.net/as02446418/article/details/47145467

给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。
给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
测试样例:
“This is nowcoder”,”is This nowcoder”
返回:true
“Here you are”,”Are you here”
返回:false

public class Same {
     public static boolean checkSam(String stringA, String stringB) {
            // write code here
            if(stringA.length()!=stringB.length())return false;

            Map<Character,Integer> map = new HashMap<Character,Integer>();
            for(int i=0;i<stringA.length();i++){
                char temp = stringA.charAt(i);
                if(map.containsKey(temp)){
                    map.put(temp,map.get(temp)+1);
                }else{
                    map.put(temp,1);
                }

            }

            for(int i=0;i<stringB.length();i++){
                char temp = stringB.charAt(i);
                if(map.containsKey(temp)){
                if(map.get(temp)>0){
                    map.put(temp,map.get(temp)-1);              
                    }else{
                        return false;
                    }
                }
                    else return false;
            }       

            return true;
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值