Problem
é¢ē®å¤§ęļ¼ē»ä½ s1, s2ļ¼é®ä½ s2ēåäø²äøęÆå¦ååØs1ēäøäøŖęåć
https://leetcode.com/problems/permutation-in-string/description/
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].
Solution: Sliding Window
Time Complexity: O(l1 + l2 * 26) = O(l1 + l2)
Space Complexity: O(26 * 2) = O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua // Running time: 12 ms class Solution { public: bool checkInclusion(string s1, string s2) { int l1 = s1.length(); int l2 = s2.length(); vector<int> c1(26); vector<int> c2(26); for (const char c : s1) ++c1[c - 'a']; for (int i = 0; i < l2; ++i) { if (i >= l1) --c2[s2[i - l1] - 'a']; ++c2[s2[i] - 'a']; if (c1 == c2) return true; } return false; } }; |