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