leetcode 01.02:判定是否互为字符串重排

import java.util.HashMap;
import java.util.Map;

/**
 * @Class CheckPermutation
 * @Description 
 * 给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
 * <p>
 * 示例 1:
 * 输入: s1 = "abc", s2 = "bca"
 * 输出: true
 * <p>
 * 示例 2:
 * 输入: s1 = "abc", s2 = "bad"
 * 输出: false
 * 说明:
 * 0 <= len(s1) <= 100
 * 0 <= len(s2) <= 100
 * @Author 
 * @Date 2020/6/23
 **/
public class CheckPermutation {
}
public static boolean checkPermutation(String s1, String s2) {
	if (s1.length() != s2.length()) {
		return false;
	}

    // 利用键值对,保存每个字符出现的次数,然后对比s2中相同字符出现的次数是否相等
	Map<Character, Integer> map = new HashMap<>();
	for (int i = 0; i < s1.length(); i++) {
		char ch = s1.charAt(i);
		if (map.containsKey(ch)) {
			int temp = map.get(ch).intValue();
			temp++;
			map.put(ch, temp);
		} else {
			map.put(ch, 1);
		}
	}

	for (int i = 0; i < s2.length(); i++) {
		char ch = s2.charAt(i);
		if (!map.containsKey(ch)) {
			return false;
		} else {
			int temp = map.get(ch);
			if (temp <= 0) return false;

			temp--;
			map.put(ch, temp);
		}
	}
	return true;
}
// 测试用例
public static void main(String[] args) {
	String s1 = "abc", s2 = "bca";
	boolean ans = checkPermutation(s1,s2);
	System.out.println("demo01 result:"+ans);

	s1 = "abc";
	s2 = "bad";        
	ans = checkPermutation(s1,s2);
	System.out.println("demo02 result:"+ans);

	s1 = "asvnpzurz";
	s2 = "urzsapzvn";
	ans = checkPermutation(s1,s2);
	System.out.println("demo03 result:"+ans);
}
posted @ 2020-06-23 14:47  枫叶艾辰  阅读(120)  评论(0编辑  收藏  举报