zoukankan      html  css  js  c++  java
  • Permutation in String

    Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/permutation-in-string
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    截取一段子字符串,然后与目标字符串比较,如果把目标字符串打乱重拍的话,那样就太烦了,效率肉眼可见的低。其实不妨想想,子字符串与目标字符串任一排列相同即可,说明我们只需要统计各字符的个数,如果各字符的个数都相等的话,那么肯定会有一种排列是符合要求的。这样一来,我们就只需统计字符串的个数并且比较,而不需要做一次全排列组合了。这样可以大幅度降低程序执行的时间。

    class Solution {
        public boolean checkInclusion(String s1, String s2) {
            int[] counts1 = new int[26];
            int len = s1.length();
            for(int i = 0; i < len; i++){
                counts1[s1.charAt(i) - 'a']++;
            }
            for(int j = 0; j <= s2.length() - len ; j++) {
                String str = s2.substring(j, j+len);
                if(count(str, counts1))
                    return true;
            }
            return false;
        }
    
        public static boolean count(String str, int[] counts) {
            int[] counts2 = new int[26];
            for(int i = 0; i < str.length(); i++) {
                counts2[str.charAt(i) - 'a']++;
            }
            for(int k = 0; k < 26; k++) {
                if(counts[k] != counts2[k])
                    return false;
            }
            return true;
        }
    }
  • 相关阅读:
    leetcode66 plusOne
    park/unpark 阻塞与唤醒线程
    leetcode55 jumpGame贪心算法
    ACID特性与事务的隔离级别
    PCB ODB++(Gerber)图形绘制实现方法
    PCB 所建不凡 AWS 技术峰会2018 • 深圳站 2018.9.20
    PCB SQL SERVER 位运算应用实例
    PCB SQL SERVER 枚举分割函数(枚举值分解函数)
    PCB SQL SERVER 正则应用实例
    PCB Genesis 外形加内角孔实现方法
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/13637488.html
Copyright © 2011-2022 走看看