[LeetCode] 567. Permutation in 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].
给2个字符串s1和s2,写一个函数能够返回是否s1的全排列中存在着一个是s2的子字符串。
虽然题目中有全排列,但跟以前的全排列的题目的解法并不一样,如果遍历s1所有全排列的情况,然后检测其是否为s2的子串,非常不高效。 其实并不需要知道s1的全排列情况,只要知道s2中一个长度和s1一样的子字符串所含的字符一样就可以了。和438. Find All Anagrams in a String 类似。
解法:滑动窗口法
Java:
public class Solution {
public boolean checkInclusion(String s1, String s2) {
int len1 = s1.length(), len2 = s2.length();
if (len1 > len2) return false; int[] count = new int[26];
for (int i = 0; i < len1; i++) {
count[s1.charAt(i) - 'a']++;
count[s2.charAt(i) - 'a']--;
}
if (allZero(count)) return true; for (int i = len1; i < len2; i++) {
count[s2.charAt(i) - 'a']--;
count[s2.charAt(i - len1) - 'a']++;
if (allZero(count)) return true;
} return false;
} private boolean allZero(int[] count) {
for (int i = 0; i < 26; i++) {
if (count[i] != 0) return false;
}
return true;
}
}
Java:
public class Solution {
public boolean checkInclusion(String s1, String s2) {
int[] map = new int[26];
int sum = s1.length();
// construct frequency map
for(int i = 0; i< s1.length(); i++){
map[s1.charAt(i) - 'a']++;
}
for(int r = 0, l = 0; r < s2.length(); r++){
char c = s2.charAt(r);
if(map[c - 'a'] > 0){
map[c - 'a']--;
sum--;
//check for permutation match.
if(sum == 0) return true;
}else{
// if there is enough number for char c or c is never seen before.
// we move left pointer next to the position where we first saw char c
// or to the r+1(we never see char c before),
//and during this process we restore the map.
while(l<= r && s2.charAt(l) != s2.charAt(r)){
map[s2.charAt(l) - 'a'] ++;
l++;
sum++;
}
l++;
}
}
return false;
}
}
Python:
def checkInclusion(self, s1, s2):
A = [ord(x) - ord('a') for x in s1]
B = [ord(x) - ord('a') for x in s2] target = [0] * 26
for x in A:
target[x] += 1 window = [0] * 26
for i, x in enumerate(B):
window[x] += 1
if i >= len(A):
window[B[i - len(A)]] -= 1
if window == target:
return True
return False
Python:
class Solution(object):
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
counts = collections.Counter(s1)
l = len(s1)
for i in xrange(len(s2)):
if counts[s2[i]] > 0:
l -= 1
counts[s2[i]] -= 1
if l == 0:
return True
start = i + 1 - len(s1)
if start >= 0:
counts[s2[start]] += 1
if counts[s2[start]] > 0:
l += 1
return False
C++:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int n1 = s1.size(), n2 = s2.size();
vector<int> m1(128), m2(128);
for (int i = 0; i < n1; ++i) {
++m1[s1[i]]; ++m2[s2[i]];
}
if (m1 == m2) return true;
for (int i = n1; i < n2; ++i) {
++m2[s2[i]];
--m2[s2[i - n1]];
if (m1 == m2) return true;
}
return false;
}
};
C++:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int n1 = s1.size(), n2 = s2.size(), left = 0;
vector<int> m(128);
for (char c : s1) ++m[c];
for (int right = 0; right < n2; ++right) {
if (--m[s2[right]] < 0) {
while (++m[s2[left++]] != 0) {}
} else if (right - left + 1 == n1) return true;
}
return n1 == 0;
}
};
C++:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int n1 = s1.size(), n2 = s2.size(), cnt = n1, left = 0;
vector<int> m(128);
for (char c : s1) ++m[c];
for (int right = 0; right < n2; ++right) {
if (m[s2[right]]-- > 0) --cnt;
while (cnt == 0) {
if (right - left + 1 == n1) return true;
if (++m[s2[left++]] > 0) ++cnt;
}
}
return false;
}
};
类似题目:
[LeetCode] 438. Find All Anagrams in a String 找出字符串中所有的变位词
All LeetCode Questions List 题目汇总
[LeetCode] 567. Permutation in String 字符串中的全排列的更多相关文章
- [LeetCode] Permutation in String 字符串中的全排列
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. I ...
- [LeetCode] Bold Words in String 字符串中的加粗单词
Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any le ...
- 567. Permutation in String字符串的排列(效率待提高)
网址:https://leetcode.com/problems/permutation-in-string/ 参考:https://leetcode.com/problems/permutation ...
- String 字符串中含有 Unicode 编码时,转为UTF-8
1.单纯的Unicode 转码 String a = "\u53ef\u4ee5\u6ce8\u518c"; a = new String(a.getBytes("UTF ...
- 将string字符串中的换行符进行替换
/** * 方法名称:replaceBlank * 方法描述: 将string字符串中的换行符进行替换为"" * */ public static String replaceBl ...
- [LeetCode] Add Bold Tag in String 字符串中增添加粗标签
Given a string s and a list of strings dict, you need to add a closed pair of bold tag <b> and ...
- 434 Number of Segments in a String 字符串中的单词数
统计字符串中的单词个数,这里的单词指的是连续的非空字符.请注意,你可以假定字符串里不包括任何不可打印的字符.示例:输入: "Hello, my name is John"输出: 5 ...
- [CareerCup] 1.1 Unique Characters of a String 字符串中不同的字符
1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot us ...
- String:(字符串)中常用的方法
package stringyiwen; //字符串中常用的方法public class StringTest03 { public static void main(String[] args) { ...
随机推荐
- YII2 更新数据不成功
起因: CLI模式,定时任务.同步其他系统中的DB数据,通过视图的方式. 历程: 原脚本已经写好,实在已经有的基础上修改,增加新的字段. 加了字段后,执行,但始终不成功,表里记录的utime也是能更新 ...
- java项目部署到LIINUX
天领导给个任务,把java项目部署到liunx服务器上.现记录步骤,方便以后查看.项目部署服务器步骤:服务器信息:弹性IP地址:xx.xx.xxx.xx账号:root密码:cjw@100 数据库信息: ...
- python - django 实现文件下载功能
使用 Django 搭建的网站中添加一个可以从服务器中下载文件的功能 (此处演示一个从网站中下载API文档的例子供参考) # 一.url urlpatterns = [ # 下载 API 接口文档 ...
- Clickhouse 性能瓶颈排查 IO过高
前几天公司clickhouse 有个查询很慢.经理一直追问为什么慢 是cpu 不够 还是IO 占用太高,还是其他的原因.于是有了以下的排查 执行该条,在不考虑优化sql 的情况下 进行性能排查 1.首 ...
- java大附件上传,支持断点续传
一. 功能性需求与非功能性需求 要求操作便利,一次选择多个文件和文件夹进行上传:支持PC端全平台操作系统,Windows,Linux,Mac 支持文件和文件夹的批量下载,断点续传.刷新页面后继续传输. ...
- WinDbg 图形界面功能(四)
二.工具栏 除了断点按钮在工具栏上的每个按钮相当于菜单命令. 每个按钮的效果的完整说明,请参阅相应的菜单命令的页. 在工具栏上的按钮具有以下效果. 按钮 描述 打开源文件为只读的文件. 等效于文件 | ...
- Binding a Xamarin.Forms WebView to ReactiveUI View Model using Custom Type Converters
引用:https://jamilgeor.com/binding-a-xamarin-forms-webview-to-reactiveui-view-model-using-custom-type- ...
- C# VS 调试 动态加载的 DLL
原文:https://www.cnblogs.com/DasonKwok/p/10510218.html 在这篇文章的底部,有提供示例的Demo,可以参考一下哦,拿来直接就可以运行. 说明: 编译类库 ...
- CF #365 DIV2 D Mishka and Interesting sum 区间异或+线段树
D. Mishka and Interesting sum time limit per test 3.5 seconds memory limit per test 256 megabytes in ...
- javascript中的indexOf与if判断的装逼写法
常规indexOf与if判断写法: if("112233".indexOf("22")>-1) { console.log("很二") ...