原题链接在这里: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:

  1. The input strings only contain lower case letters.
  2. 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:

 class Solution {
public boolean checkInclusion(String s1, String s2) {
if(s1 == null || s2 == null || s1.length() > s2.length()){
return false;
} int [] map = new int[256];
for(int i = 0; i<s1.length(); i++){
map[s1.charAt(i)]++;
} int walker = 0;
int runner = 0;
int sum = s1.length();
while(runner < s2.length()){
if(map[s2.charAt(runner++)]-- > 0){
sum--;
} if(sum == 0){
return true;
} if(runner-walker==s1.length() && map[s2.charAt(walker++)]++ >= 0){
sum++;
}
} return false;
}
}

类似Find All Anagrams in a String.

最新文章

  1. 疑难问题解决备忘录(3)——ubuntu12.04配置vsftp本地用户登录
  2. 理解 Keystone 核心概念 - 每天5分钟玩转 OpenStack(18)
  3. CheckLogin
  4. 剑指 Offer 题目汇总索引
  5. Effective C++ -----条款49:了解new-handler 的行为
  6. 编译android源码官方教程(5)编译完之后刷机、编译fastboot
  7. git 使用(二)
  8. 二、有限状态机(FSM)
  9. ssh自动登录的4种实现方法
  10. 转:有事务处理的NoSQL数据库
  11. 求绝对值,hdu-2003
  12. mac os vim 乱码
  13. IIS配置HTTPS
  14. Python-接口自动化(十)
  15. pandas数据的分组与分列
  16. P1091 合唱队形 最长上升子序列
  17. mpvue 转小程序实践总结
  18. Mac OS X系统 用dd命令将iso镜像写入u盘
  19. 查看线程的进程id
  20. PReLU

热门文章

  1. Spring Cloud实战
  2. Verilog HDL Test Bench
  3. bzoj 1798 双标记区间修改线段树
  4. poj3308 Paratroopers 最大流 最小点权覆盖
  5. Centos7 使用Dockerfile 制作自己的Dotnetcore程序镜像
  6. iOS安全系列之 HTTPS
  7. Nginx配置请求转发location及rewrite规则
  8. C++/C extern关键字详解 EntryPointNotFoundException处理
  9. 说说C++多重继承
  10. 迁移到阿里云后,NTKO控件报存word 报文件存取错误,请检查网络传输。