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

欣赏一下别人写的,所说下面两道题用的是同一思路,记录一下

https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92015/ShortestConcise-JAVA-O(n)-Sliding-Window-Solution

https://leetcode.com/problems/minimum-window-substring/discuss/26808/here-is-a-10-line-template-that-can-solve-most-substring-problems

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的更多相关文章

  1. 【leetcode】438. Find All Anagrams in a String

    problem 438. Find All Anagrams in a String solution1: class Solution { public: vector<int> fin ...

  2. 438. Find All Anagrams in a String

    原题: 438. Find All Anagrams in a String 解题: 两个步骤 1)就是从s中逐步截取p长度的字符串 2)将截取出的字符串和p进行比较,比较可以用排序,或者字典比较(这 ...

  3. [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 ...

  4. 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 ...

  5. 【LeetCode】438. Find All Anagrams in a String 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 滑动窗口 双指针 日期 题目地址:https://l ...

  6. [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 ...

  7. 【leetcode❤python】 438. Find All Anagrams in a String

    class Solution(object):    def findAnagrams(self, s, p):        """        :type s: s ...

  8. 438 Find All Anagrams in a String 找出字符串中所有的变位词

    详见:https://leetcode.com/problems/find-all-anagrams-in-a-string/description/ C++: class Solution { pu ...

  9. [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 ...

随机推荐

  1. servlet中的ServletContext对象

    ServletContext官方叫Servlet上下文.服务器会为每一个Web应用创建一个ServletContext对象.这个对象全局唯一,而且Web应用 中的所有Servlet都共享这个对象(在整 ...

  2. 设备像素,CSS像素,设备独立像素

    1.概念 设备像素(device pixel)简写DP 设备像素又称 **物理像素** ,是设备能控制显示的最小单位,我们可以把它看做显示器上的一个点.我们常说的 1920x1080像素分辨率就是用的 ...

  3. 细说Web API中的Blob

    在一般的Web开发中,很少会用到Blob,但Blob可以满足一些场景下的特殊需求.Blob,Binary Large Object的缩写,代表二进制类型的大对象.Blob的概念在一些数据库中有使用到, ...

  4. Angular2入门系列(五)———— 路由参数设置

    Angular2入门系列(五)---- 路由参数设置路由配置: { path: '', component: CarProFile, children: [ { path: 'add', compon ...

  5. 深入解析丨母婴App如何迅速收割2W新用户?

    在讲案例前,我们需要先说一下精细化分析. 我们常说的精细化分析,就是一个持续"解构"的过程,通过像漏斗.留存.细分等高级分析功能,将"整体"按照事件属性解构成& ...

  6. CCF201604-2俄罗斯方块

    问题描述 俄罗斯方块是俄罗斯人阿列克谢·帕基特诺夫发明的一款休闲游戏. 游戏在一个15行10列的方格图上进行,方格图上的每一个格子可能已经放置了方块,或者没有放置方块.每一轮,都会有一个新的由4个小方 ...

  7. px,rem,em 通过媒体查询统一的代码

    @media only screen and (max-width: 1080px), only screen and (max-device-width:1080px) { html,body { ...

  8. 9. Lab: file system

    https://pdos.csail.mit.edu/6.S081/2021/labs/fs.html 1. Large files (moderate) 1.1 要求 Modify bmap() s ...

  9. Windows中Nginx配置nginx.conf不生效解决方法

    转:https://lucifer.blog.csdn.net/article/details/83860644?utm_medium=distribute.pc_relevant.none-task ...

  10. RFC 标准文档

    RFC 标准文档 什么是 RFC ? RFC(Request For Comments)意即"请求评论",包含了关于Internet的几乎所有重要的文字资料.如果你想成为网络方面的 ...