面试金典系列3--确定两串乱序同构

面试金典系列1--确定两串乱序同构


给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。

给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。

测试样例:
"This is nowcoder","is This nowcoder"
返回:true
"Here you are","Are you here"
返回:false
解法:

import java.util.*;
 
public class Same {
    public boolean checkSam(String stringA, String stringB) {
        // write code here
        if (stringA == null || stringA.length() < 1 || stringB == null || stringB.length() < 1
                || stringA.length() != stringB.length()) {
            return false;
        }
        boolean resu = true;
        HashMap<Character, Integer> mapA = getMap(stringA);  
        HashMap<Character, Integer> mapB = getMap(stringB);
        for (Map.Entry<Character, Integer> entry : mapA.entrySet()) {
            char key = entry.getKey();
            int value = entry.getValue();
            if (!mapB.containsKey(key) || value != mapB.get(key)) {
                resu = false;
                break;
            }
        }
        return resu;
    }
 
    public HashMap<Character, Integer>getMap(String str) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); ++i) {
            Integer tmp = map.get(str.charAt(i));
            tmp = (tmp == null) ? new Integer(1) : (tmp + 1);
            map.put(str.charAt(i), tmp);
        }
        return map;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值