zoukankan      html  css  js  c++  java
  • 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);
    }
    
  • 相关阅读:
    .bat文件打开指定网页,并运行jar包
    jar包制作一个可执行文件
    如何让局域网其他电脑通过IP直接访问自己电脑的网站
    Sypder 安装和使用
    tomcat服务器输入localhost可以访问,ip无法访问解决办法
    【转载】高性能网站建设
    网站优化
    JavaWeb 项目开发中的技术总结
    反射工具类——ReflectUtils
    Ajax 的缺点
  • 原文地址:https://www.cnblogs.com/fyusac/p/13182032.html
Copyright © 2011-2022 走看看