438. Find All Anagrams in a String - LeetCode
Question
438. Find All Anagrams in a String
Solution
题目大意:给两个字符串,s和p,求p在s中出现的位置,p串中的字符无序,ab=ba
思路:起初想的是求p的全排列,保存到set中,遍历s,如果在set中出现,s中的第一个字符位置保存到结果中,最后返回结果。这种思路执行超时。可能是求全排列超时的。
思路2:先把p中的字符及字符出现的次数统计出来保存到map中,再遍历s,这个思路和169. Majority Element - LeetCode中提到的创新解法类似
Java实现:
public List<Integer> findAnagrams(String s, String p) {
List<Integer> ans = new ArrayList<>();
if (s.length() <= p.length()) return ans;
// 构造map,并初始化target
Map<Character, Bo> map = new HashMap<>();
for (char tmp : p.toCharArray()) {
Bo bo = map.get(tmp);
if (bo == null) {
bo = new Bo();
map.put(tmp, bo);
}
bo.target++;
}
// 前p.length()项
for (int i = 0; i < p.length(); i++) {
char cur = s.charAt(i);
Bo bo = map.get(cur);
if (bo != null) {
bo.cur++;
}
}
if (allOne(map)) ans.add(0);
for (int i = p.length(); i < s.length(); i++) {
char cur = s.charAt(i);
if (map.get(cur) != null) map.get(cur).cur++;
char last = s.charAt(i - p.length());
if (map.get(last) != null) map.get(last).cur--;
if (allOne(map)) ans.add(i - p.length() + 1);
}
return ans;
}
public boolean allOne(Map<Character, Bo> map) {
for (Map.Entry<Character, Bo> entry : map.entrySet()) {
if (entry.getValue().cur != entry.getValue().target) return false;
}
return true;
}
class Bo {
int cur; // 当前数
int target; // 目标数
public Bo() {
this(0, 0);
}
public Bo(int cur, int target) {
this.cur = cur;
this.target = target;
}
}
Discuss
欣赏一下别人写的,所说下面两道题用的是同一思路,记录一下
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<>();
if (s == null || s.length() == 0 || p == null || p.length() == 0) return list;
int[] hash = new int[256]; //character hash
//record each character in p to hash
for (char c : p.toCharArray()) {
hash[c]++;
}
//two points, initialize count to p's length
int left = 0, right = 0, count = p.length();
while (right < s.length()) {
//move right everytime, if the character exists in p's hash, decrease the count
//current hash value >= 1 means the character is existing in p
if (hash[s.charAt(right++)]-- >= 1) count--;
//when the count is down to 0, means we found the right anagram
//then add window's left to result list
if (count == 0) list.add(left);
//if we find the window's size equals to p, then we have to move left (narrow the window) to find the new match window
//++ to reset the hash because we kicked out the left
//only increase the count if the character is in p
//the count >= 0 indicate it was original in the hash, cuz it won't go below 0
if (right - left == p.length() && hash[s.charAt(left++)]++ >= 0) count++;
}
return list;
}
public List<Integer> findAnagrams(String s, String p) {
char[] ptrn = p.toCharArray();
char[] str = s.toCharArray();
int[] w = new int[26];
for(char c : ptrn) w[c - 'a']++;
int start = 0;
List<Integer> result = new LinkedList<>();
for(int i = 0; i<str.length; i++){
int cIndex = str[i] - 'a';
w[cIndex]--;
// the crucial bit, if we have seen the character too many times
// or it is a character that is not in the pattern, rewind the starting index
while(w[cIndex] < 0){
w[str[start] - 'a']++;
start++;
}
if(i - start + 1 == ptrn.length){
result.add(start);
w[str[start] - 'a']++;
start++;
}
}
return result;
}
438. Find All Anagrams in a String - LeetCode的更多相关文章
- 【leetcode】438. Find All Anagrams in a String
problem 438. Find All Anagrams in a String solution1: class Solution { public: vector<int> fin ...
- 438. Find All Anagrams in a String
原题: 438. Find All Anagrams in a String 解题: 两个步骤 1)就是从s中逐步截取p长度的字符串 2)将截取出的字符串和p进行比较,比较可以用排序,或者字典比较(这 ...
- [LeetCode] 438. Find All Anagrams in a String 找出字符串中所有的变位词
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings ...
- LeetCode 438. Find All Anagrams in a String (在字符串中找到所有的变位词)
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings ...
- 【LeetCode】438. Find All Anagrams in a String 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 滑动窗口 双指针 日期 题目地址:https://l ...
- [leetcode]438. Find All Anagrams in a String找出所有变位词
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings ...
- 【leetcode❤python】 438. Find All Anagrams in a String
class Solution(object): def findAnagrams(self, s, p): """ :type s: s ...
- 438 Find All Anagrams in a String 找出字符串中所有的变位词
详见:https://leetcode.com/problems/find-all-anagrams-in-a-string/description/ C++: class Solution { pu ...
- [LC] 438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings ...
随机推荐
- 基于Node的React图片上传组件实现
写在前面 红旗不倒,誓把JavaScript进行到底!今天介绍我的开源项目 Royal 里的图片上传组件的前后端实现原理(React + Node),花了一些时间,希望对你有所帮助. 前端实现 遵循R ...
- Angular2入门系列(五)———— 路由参数设置
Angular2入门系列(五)---- 路由参数设置路由配置: { path: '', component: CarProFile, children: [ { path: 'add', compon ...
- 解决使用 swiper 常见的问题
使用 swiper 的过程中个人总结 1. swiper插件使用方法, 直接查看文档 swiper基础演示 swiper API文档 2.swiper近视初始化时, 其父级元素处于隐藏状态(displ ...
- python-图的字典表示
图的字典表示.输入多行字符串,每行表示一个顶点和该顶点相连的边及长度,输出顶点数,边数,边的总长度.比如上图0点表示:{'O':{'A':2,'B':5,'C':4}}.用eval函数处理输入,eva ...
- 记住用户名和登录密码+虚拟机没有root权限解决办法
今日所学: 记住用户名和登录密码 用adb查看保存文件内容 如何使用adb 如何安装adb-百度经验 遇到的问题: 用adb查看文件时,没有权限访问data文件 出现原因:google play虚拟机 ...
- EL表达式详解(常用表达式以及取值)
EL表达式 学习总结 一. El表达式概念 二. El中的表达式 1. 算术表达式 2. 比较表达式 3. 逻辑表达式 4. 三元表达式 5. 判空表达式 三.EL 从四个作用域中取值 1. 概念 2 ...
- Markdown基础语法规则
你好,世界.粗体,斜体,测试,弟弟,H2O 论文题目 一级标题 二级标题 三级标题 1 2 3 点击此链接打开网址 公式 \(y = \sin x\) \[ y = \frac{1}{x} \] dd ...
- C++篇:第四章_函数_知识点大全
C++篇为本人学C++时所做笔记(特别是疑难杂点),全是硬货,虽然看着枯燥但会让你收益颇丰,可用作学习C++的一大利器 五.函数 (一)函数使用规则 函数的定义不能嵌套但调用可以嵌套 在函数调用时,如 ...
- NodeJS学习day1
今天主要学习的IO操作 const fs = require('fs') fs.readFile('./files/11.txt','utf-8',function(err,daraStr){ //读 ...
- go的调度
操作系统根据资源访问权限的不同,体系架构可以分为用户空间和内核空间:内核空间主要操作访问CPU资源,IO资源,内存资源等硬件资源,为应用程序提供最基本的基础资源:用户空间是上层应用程序的固定活动空间, ...