[LintCode] Permutation in String

 约 3 分钟

Problem

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.

Example

Example 1:

Input:s1 = "ab" s2 = "eidbaooo"
Output:True
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:

Input:s1= "ab" s2 = "eidboaoo"
Output: False

Solution

public class Solution {
    /**
     * @param s1: a string
     * @param s2: a string
     * @return: if s2 contains the permutation of s1
     */
    public boolean checkInclusion(String s1, String s2) {
        int len = s1.length();
        for (int i = 0; i <= s2.length()-len; i++) {
            if (isPermutation(s2.substring(i, i+len), s1)) return true;
        }
        return false;
    }
    
    //use the method of #String Permutation
    public boolean isPermutation(String s1, String s2) {
        if (s1 == null) return s2 == null;
        if (s2 == null) return s1 == null;
        if (s1.length() != s2.length()) return false;
        
        int[] dict = new int[256];
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        for (char ch: c1) {
            dict[(int)ch]++;
        }
        for (char ch: c2) {
            dict[(int)ch]--;
            if (dict[(int)ch] < 0) return false;
        }

        return true;
    }
}
阅读 767

推荐阅读
Road to Glory
用户专栏

對酒當歌,人生幾何?譬如朝露,去日苦多。

22 人关注
639 篇文章
专栏主页
目录