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. Numpy对数组按索引查询

    Numpy对数组按索引查询 三种索引方法: 基础索引 神奇索引 布尔索引 基础索引 一维数组 和Python的List一样 二维数组 注意:切片的修改会修改原来的数组 原因:Numpy经常要处理大数组 ...

  2. (6) 结论,摘要与题目_Conclusion, Abstract, and Title【论文写作】

  3. Creating a File Mapping Object

    创建一个文件映射对象 映射一个文件的第一步是通过调用CreateFile函数来打开一个文件.为了确保其他的进程不能对文件已经被映射的那一部分进行写操作,你应该以唯一访问(exclusive acces ...

  4. 来扯点ionic3[7] LocalStorage的使用—以登录和注销为例

    一般意义上,一个互联网 APP 中的数据主自与服务器的交互,但是对于有些数据,我们希望获取到它们以后能保存,并在全局环境使用,比如用户数据--我们不希望在每个页面都从服务器拉取一遍.这时我们就可以利用 ...

  5. Java基础之浅谈接口

    前言 前几篇文章我们已经把Java的封装.继承.多态学习完了,现在我们开始比较便于我们实际操作的学习,虽然它也是Java基础部分,但是其实入门容易,精通很难. 我认真的给大家整理了一下这些必须学会.了 ...

  6. Struts2-值栈的定义

    1.值栈的概念:在Struts2里面提供本身的一种储存机制,类似于域对象,可以存值和取值(可以类比Servlet中的域对象->request,session,application) 2.具体操 ...

  7. C++的"开始" Hello World! 你好世界!

    # C++的"开始" Hello World! 你好世界! ```C++ // 第一个程序 //代表注释这一行 #include <iostream> //c++专属头 ...

  8. Java之万年历

    @(文章目录) 二.Java之万年历 2.1 要求 输入年份: 输入月份: 输出某年某月的日历. 2.2 思路 实现从控制台接收年和月,判断是否是闰年(判断是否是闰年:能被4整除但不能被100整除:或 ...

  9. CAN总线收发节点设计

    CAN总线收发节点设计 写在前面 这是微机接口的一个项目作业. 这段时间一直在宿舍隔离,没办法进行焊接和测试,但原理和代码已经在学习板子上经过验证. 设计目标 CAN在工业现场大量应用,尤其是汽车工业 ...

  10. 001_iBase4J学习之环境搭建

    目录 序言 正文 第一关.拉取项目 第二关.导入数据库 第三关.修改 JDBC 配置文件 第四关.环境搭建,修改 nginx 设置 第五关.添加地址白名单 尾声 序言 大家好,我是白墨! 本次的目标是 ...