LeetCode 567. Permutation in String
原题链接在这里: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].
题解:
如何知道s1是s2某一段的permutation. 只要确定这一段的char count相等就行.
利用sliding window 长度为s1.length累计char count.
Note: check sum == 0 before moving walker. "ab", "bao", runner = 2, walker = 0, check sum == 0.
Time Complexity: O(n). n = s1.length()+s2.length().
Space: O(1).
AC Java:
1 class Solution { 2 public boolean checkInclusion(String s1, String s2) { 3 if(s1 == null || s2 == null || s1.length() > s2.length()){ 4 return false; 5 } 6 7 int [] map = new int[256]; 8 for(int i = 0; i<s1.length(); i++){ 9 map[s1.charAt(i)]++; 10 } 11 12 int walker = 0; 13 int runner = 0; 14 int sum = s1.length(); 15 while(runner < s2.length()){ 16 if(map[s2.charAt(runner++)]-- > 0){ 17 sum--; 18 } 19 20 if(sum == 0){ 21 return true; 22 } 23 24 if(runner-walker==s1.length() && map[s2.charAt(walker++)]++ >= 0){ 25 sum++; 26 } 27 } 28 29 return false; 30 } 31 }
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 编码之道,道心破碎。
· 记一次 .NET 某发证机系统 崩溃分析
· 微服务架构学习与思考:SOA架构与微服务架构对比分析
· tomcat为什么假死了
· 聊一聊 Linux 上对函数进行 hook 的两种方式
· 一周 Star 破万的开源项目「GitHub 热点速览」
· 编码之道,道心破碎。
· 千万级大表,如何做性能调优?
· 不写代码,让 AI 生成手机 APP!保姆级教程
· 知名开源项目Alist被收购!惹程序员众怒,开团炮轰甲方
2017-01-17 LeetCode 437. Path Sum III