python 字符串的排列

问题描述:

给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。

换句话说,第一个字符串的排列之一是第二个字符串的子串。

输入: s1 = “ab” s2 = “eidbaooo”
输出: True
解释: s2 包含 s1 的排列之一 (“ba”).

输入: s1= “ab” s2 = “eidboaoo”
输出: False

注意:

  1. 输入的字符串只包含小写字母
  2. 两个字符串的长度都在 [1, 10,000] 之间

解决方法:

# 基本思路是 比较 s1中的每个字母在 s2的子串中出现的次数
# s2的子串长度 等于 s1 的长度

class Solution(object):
    def checkInclusion(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        
        s1_len = len(s1)
        s2_len = len(s2)
        
        start_index = 0
        end_index = start_index + s1_len
        
        element_hash = {}
        for element in s1:
            if element not in element_hash.keys():
                element_hash[element] = 1
            else:
                element_hash[element] +=1
        
        print element_hash
        
        while end_index <= s2_len:
            
            split_str = s2[start_index : end_index]
            
            for character_type, character_count in element_hash.items():
                if character_type not in split_str:
                    break    
                elif character_count != split_str.count(character_type):
                    break
        
            else:
                return True
            
            start_index += 1
            end_index += 1
        
        return False

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值