[LeetCode-567][字符串的排列][Permutation in String]

原题

链接:https://leetcode-cn.com/problems/permutation-in-string

【中文】

给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。
示例1:
输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").
 
示例2:
输入: s1= "ab" s2 = "eidboaoo"
输出: False
 
注意:
    输入的字符串只包含小写字母
    两个字符串的长度都在 [1, 10,000] 之间

【英文】

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 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
 
Note:
    The input strings only contain lower case letters.
    The length of both given strings is in range [1, 10,000].

题解思路:

  题目中是对目标子串p的各种组合的查找,即在字符串s中查找子串中的字符均在p中,且出现次数与目标子串p中的次数即可。采用滑动窗口方法。

  此题与LeetCode 438类似,可见[LeetCode-438][找到字符串中所有字母异位词][Find All Anagrams in a String]。

代码: 

bool checkInclusion(char * s1, char * s2){
    int mark[255] = {0};
    int s1Len = strlen(s1);
    int s2Len = strlen(s2);
    int i;
    int startPos = 0;
    for (i = 0; i < s1Len; i++) {
        mark[s1[i]]++;
    }
    int l = 0;
    int r = 0;
    int len = 0;
    for(l= 0, r = 0, len = 0; r < s2Len; r++) {
        mark[s2[r]]--;
        if (mark[s2[r]] >= 0) {
            len++;
        }
        while(r - l + 1 > s1Len) {
            mark[s2[l]]++;
            if (mark[s2[l]] > 0) {
                len--;
            }
            l++;
        }
        if(len == s1Len) {
            return true;
        }
    }
    return false;
}

 

posted @ 2020-02-06 22:15  稀里糊涂的胡闹  阅读(91)  评论(0)    收藏  举报