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. Python中查看变量的类型,内存地址,所占字节的大小

    查看变量的类型 #利用内置type()函数 >>> nfc=["Packers","49"] >>> afc=[" ...

  2. 分压杯频LLC变换器

  3. onsubmit阻止表单提交

    在实际开发中往往会遇到检查表单数据的合法性,如果数据不合法,就不让其提交. <!DOCTYPE html> <html> <head> <meta chars ...

  4. Java中读取 .properties 和 .xml 文件

    配置文件内容获取 总结内容 1. Java中为什么要使用配置文件 2. Java中常用的配置文件类型有哪些以及它们的特点 Properties配置文件 XML配置文件 总结 总结内容 1. Java中 ...

  5. nodejs创建服务器

      'use strict'; //加载http模块: const http = require('http'); //创建一个http服务: const server = http.createSe ...

  6. Spring Boot-切换嵌入式Servlet容器

    首先我们先查看Spring Boot中支持几种嵌入式容器 选中ConfigurableWebServerFactory类,点击ctrl+h键,查看 切换到jetty容器步骤如下 1.排除掉tomcat ...

  7. Spring5-IOC底层原理

    1.什么是IOC (1)控制反转,把对象创建和对象之间的调用过程,交给Spring进行管理 (2)使用IOC目的:为了降低耦合度 2.IOC底层原理 (1)xml解析.工厂模式.反射

  8. Hash冲突以及解决

    哈希函数:它把一个大范围的数字哈希(转化)成一个小范围的数字,这个小范围的数对应着数组的下标.使用哈希函数向数组插入数据后,这个数组就是哈希表. 冲突 当冲突产生时,一个方法是通过系统的方法找到数组的 ...

  9. 谈谈.NET Core下如何利用 AsyncLocal 实现共享变量

    前言 在Web 应用程序中,我们经常会遇到这样的场景,如用户信息,租户信息本次的请求过程中都是固定的,我们希望是这种信息在本次请求内,一次赋值,到处使用.本文就来探讨一下,如何在.NET Core 下 ...

  10. AcWing周赛43

    AcWing周赛43 题源:https://www.acwing.com/activity/content/1233/ 4314. 三元组 直接暴力做就是了,我一开始还在找规律..悲 我滴代码 #in ...