原题:
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
思路:判断s2的连续子串中,是否存在s1的任意置换。判断a和b是否互为置换,即判断字符串a和b所包含的字母种类和对应的个数是否相等。遍历s2即可解,算法复杂度为o(n)。
python代码:
class Solution(object):
# 判断两个字典是否相等,由于key数量不超过26,所以复杂度为o(1)
def is_Equal(self,dict1,dict2):
dict1_keys=dict1.keys()
for i in range(0,len(dict1_keys)):
if((dict1_keys[i] in dict2)and(dict1[dict1_keys[i]]==dict2[dict1_keys[i]])):
continue
else:
return False
return True
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
# 构造dict_a
dict_a={}
for i in range(0,len(s1)):
if(s1[i] in dict_a):
dict_a[s1[i]]+=1
else:
dict_a[s1[i]]=1
# s2长度小于s1的情况
if(len(s2)<len(s1)):
return False
# 遍历s2,并不断更新dict_b
dict_b={}
for i in range(0,len(s2)):
# 增加一位,注意增加的时候是否需要新增键
if(s2[i] in dict_b):
dict_b[s2[i]]+=1
else:
dict_b[s2[i]]=1
# 减去一位,注意减少的时候是否需要减少键
if(i>=len(s1)):
dict_b[s2[i-len(s1)]]-=1
if(dict_b[s2[i-len(s1)]]==0):
del dict_b[s2[i-len(s1)]]
if(i>=(len(s1)-1)):
if(self.is_Equal(dict_a,dict_b)):
return True
return False
c++代码:(思路和python完全一样)
class Solution {
public:
bool is_Equal(map<char,int> m1,map<char,int> m2){
if(m1.size()!=m2.size())
return false;
map <char,int>::iterator m1_Iter;
map <char,int>::iterator m2_Iter;
for(m1_Iter=m1.begin(),m2_Iter=m2.begin();m1_Iter!=m1.end(),m2_Iter!=m2.end();m1_Iter++,m2_Iter++)
if(((m1_Iter->first)!=(m2_Iter->first))||((m1_Iter->second)!=(m2_Iter->second)))
return false;
return true;
}
bool checkInclusion(string s1, string s2) {
map<char,int> m1;
map<char,int> m2;
if(s1.length()>s2.length())
return false;
for(int i=0;i<s1.length();i++){
map<char,int>::iterator m1_Iter;
m1_Iter=m1.find(s1[i]);
if(m1_Iter==m1.end())
m1[s1[i]]=1;
else
m1[s1[i]]++;
}
for(int i=0;i<s2.length();i++){
map<char,int>::iterator m2_Iter;
m2_Iter=m2.find(s2[i]);
if(m2_Iter==m2.end())
m2[s2[i]]=1;
else
m2[s2[i]]++;
if(i>=s1.length())
m2[s2[i-s1.length()]]--;
if(m2[s2[i-s1.length()]]==0){
map<char,int>::iterator m2_Del;
m2_Del=m2.find(s2[i-s1.length()]);
m2.erase(m2_Del);
}
if(i>=(s1.length()-1))
if(is_Equal(m1,m2))
return true;
}
return false;
}
};
其实用python的dict和c++的map求解这道题效率不见得高,主要是平时用得少,强行熟悉和复习一遍!