`
bcyy
  • 浏览: 1827234 次
文章分类
社区版块
存档分类
最新评论

Substring with Concatenation of All Words -- LeetCode

 
阅读更多
原题链接:http://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/

这道题看似比较复杂,其实思路和Longest Substring Without Repeating Characters差不多。因为那些单词是定长的,所以本质上和单一个字符一样。和Longest Substring Without Repeating Characters的区别只在于我们需要维护一个字典,然后保证目前的串包含字典里面的单词有且仅有一次。思路仍然是维护一个窗口,如果当前单词在字典中,则继续移动窗口右端,否则窗口左端可以跳到字符串下一个单词了。假设源字符串的长度为n,字典中单词的长度为l。因为不是一个字符,所以我们需要对源字符串所有长度为l的子串进行判断。做法是i从0到l-1个字符开始,得到开始index分别为i, i+l, i+2*l, ...的长度为l的单词。这样就可以保证判断到所有的满足条件的串。因为每次扫描的时间复杂度是O(2*n/l)(每个单词不会被访问多于两次,一次是窗口右端,一次是窗口左端),总共扫描l次(i=0, ..., l-1),所以总复杂度是O(2*n/l*l)=O(n),是一个线性算法。空间复杂度是字典的大小,即O(m*l),其中m是字典的单词数量。代码如下:

public ArrayList<Integer> findSubstring(String S, String[] L) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    if(S==null || S.length()==0 || L==null || L.length==0)
        return res;
    HashMap<String,Integer> map = new HashMap<String,Integer>();
    for(int i=0;i<L.length;i++)
    {
        if(map.containsKey(L[i]))
        {
            map.put(L[i],map.get(L[i])+1);
        }
        else
        {
            map.put(L[i],1);
        }
    }
    for(int i=0;i<L[0].length();i++)
    {
        HashMap<String,Integer> curMap = new HashMap<String,Integer>();
        int count = 0;
        int left = i;
        for(int j=i;j<=S.length()-L[0].length();j+=L[0].length())
        {
            String str = S.substring(j,j+L[0].length());
            
            if(map.containsKey(str))
            {
                if(curMap.containsKey(str))
                    curMap.put(str,curMap.get(str)+1);
                else
                    curMap.put(str,1);
                if(curMap.get(str)<=map.get(str))
                    count++;
                else
                {
                    while(curMap.get(str)>map.get(str))
                    {
                        String temp = S.substring(left,left+L[0].length());
                        curMap.put(temp,curMap.get(temp)-1);
                        if(curMap.get(temp)<map.get(temp))
                            count--;
                        left += L[0].length();
                    }
                }
                if(count == L.length)
                {
                    res.add(left);
                    //if(left<)
                    String temp = S.substring(left,left+L[0].length());
                    curMap.put(temp,curMap.get(temp)-1);
                    count--;
                    left += L[0].length();
                }
            }
            else
            {
                curMap.clear();
                count = 0;
                left = j+L[0].length();
            }
        }
    }
    return res;
}
这种移动窗口的方法在字符串处理的问题中非常常见,是一种可以把时间复杂度降低到线性的有效算法,大家可以熟悉一下。还有非常类似的题目Minimum Window Substring,思路完全一样,只是移动窗口的规则稍微不同而已。

分享到:
评论

相关推荐

    leetcode跳跃-LeetCode:leetcode中的练习

    leetcode 跳跃 LeetCode Exercises from leetcode. All the exercises is uesd by microsoft to interview. The following is the number of the questions form Leetcode. 4 寻找两个正序数组的中位数 median of ...

    dna匹配leetcode-leetcode:leetcode刷题

    Concatenation of All Words 哈希表 注意匹配方向 Valid Sudoku 数组 遍历 Sudoku Solver 深度优先遍历 回溯 先检查后修改 Group Anagrams 排序 unordered_map Minimum Window Substring 两个指针遍历 map Maximal ...

    LeetCode最全代码

    Here is the classification of all `468` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and...

    leetcode卡-leetcode-weekly-contest-186:第186届LeetCode周赛

    leetcode卡leetcode-weekly-contest-186 第 186 届 LeetCode 周赛 问题清单 拆分字符串后的最大分数 Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty...

    约瑟夫环leetcode-leetcode-everyday:leetcode-每天

    约瑟夫环 leetcode leetcode 每日一题 8 字符串转换整数 (atoi) 42 接雨水 289 生命游戏(未操作表示状态) 820 ...substring不能用的话用stringbuilder,还可以有个取余的骚操作 jz53-1 在排序数组中查

    leetcode题库-leetcode-web:以Web形式展示LeetCode题解,基于PythonFlask

    leetcode题库 LeetCode-Web 初始化 前端库依赖 下载,并将jquery-3.x.x.min.js移动到static目录下。 下载,并将semantic.min.js、semantic.min.css、components和themes...longest-substring-without-repeating-charac

    leetcode答案-LeetCode-Longest_Substring_Without_Repeating_Characters:Leet

    答案LeetCode-Longest_Substring_Without_Repeating_Characters 这是LeetCode上“最长子串无重复字符”问题的解决方案。 问题描述:给定一个字符串,求没有重复字符的最长子串的长度。 示例 1:输入:“abcabcbb” ...

    leetcode题库-LeetCode-Go:用GO回答LeetCode

    leetcode题库 LeetCode-Go 理论基础 见Note 脑图 TODO 待填充 算法题 面试高频出现,以及一些非常经典重要的算法题优先 题目列表 No Title Link Solution Acceptance Difficulty Topics Solution 0001 Two Sum 46.1%...

    分割数组求最大差值leetcode-Leetcode-Road:LeetCode刷题记录

    分割数组求最大差值leetcode LeetCode 学习之路 记录自己完成LeetCode的代码和结果。 序号 中文名称 英文名称 通过率 难度 1 Two Sum 47.0% 简单 2 Add Two Numbers 36.0% 中等 3 Longest Substring Without ...

    颜色分类leetcode-leetcode-[removed]我对Leetcode问题的解决方案

    颜色分类leetcode My Leetcode Problems Solutions Using javascript(ES6) 1 Two Sum 两数之和 5 Longest Palindromic Substring 最长回文子串 7 Reverse Integer 整数反转 9 Palindrome Number 回文数 11 Container...

    leetcode中国-LeetCode-Swift:LeetCode算法题Swift实现

    leetcode中国 LeetCode-Swift LeetCode算法题Swift实现 从2020年6月10日开始挑战每日刷算法,至少完成一道,让我们拭目以待! No. Title Chinese Difficulty Router 0001 Two Sum Easy 0002 Add Two Numbers Medium ...

    lrucacheleetcode-leetcode-1:leetcode-1

    of Two Sorted Arrays 求两有序数列的中位数,可泛化为求两有序数列的第k位数,二分法 5. Longest Palindromic Substring 最长回文子串,补符号,记忆 6. ZigZag Conversion 观察规律 7. Reverse Integer 翻转整数 8...

    gasstationleetcode-leetcode-rust:莱特代码休息

    3-longest-substring-without-repeating-characters 7 cargo run --bin 7-reverse-integer 9 cargo run --bin 9-palindrome-number 13 cargo run --bin 13-roman-to-integer 14 cargo run --bin 14-longest-common-...

    leetcode实现strstr-leetcode-js:js刷leetcode

    leetcode实现strstr leetcode-js 记录刷leetcode分析过程,希望一点点进步! leetcode地址 刷题顺序 按照顺序刷第一遍,记录实现思路,自己的优化方案,并研究高票大佬的思路。 已完成题目归档 序号 题目 题解 实现...

    javalruleetcode-leetcode-java:力码笔记

    leetcode leetcode-java leetcode刷题笔记 已做题目列表 1.Two Sum 3.Longest Substring Without Repeating Characters 5.Longest Palindromic Substring 20.Valid Parentheses 26.Remove Duplicates from Sorted ...

    leetcode2sumc-LeetCode-3.Longest_Substring_Without_Repeating_Characters

    LeetCode-3.Longest_Substring_Without_Repeating_Characters 给定一个字符串,找出没有重复字符的最长子字符串的长度。 示例 1: 输入:“abcabcbb” 输出:3 解释:答案是“abc”,长度为 3。 解决方案 Python3:...

    javalruleetcode-LeetCode:LeetCode算法问题

    With Most Water LeetCode 19 Remove Nth Node From End of List LeetCode 42 Trapping Rain Water LeetCode 61 RotateList LeetCode 75 Sort Colors LeetCode 125 Valid Palindrome LeetCode 167 Two Sum II - ...

    LeetCodeTrain:这是来自LeetCode的已解决任务的存储库

    CoinChange.java - //leetcode.com/problems/coin-change/ ProductOfArrayExceptSelf.java - //leetcode.com/problems/product-of-array-except-self/ LongestRepeatingCharacterReplacement.java - //leetcode....

    leetcode安卓-leetcode-cn.com:给自己看的leetcode刷题记录

    leetcode安卓 leetcode-cn.com 给自己看的leetcode刷题记录 动态规划 5. 最长回文子串 class Solution { public String longestPalindrome(String s) { String result = ""; int length = s.length(); // 动态规划,...

    leetcode答案-SH_LeetCode:LeetCode-Swift

    leetcode 答案 SH_LeetCode LeetCode-Swift解答记录(Answer records of LeetCode) 11月21日 更新:添加README文件以及LeetCode前三题代码(Add README.md and Code for the first three questions) 1. 两数之和...

Global site tag (gtag.js) - Google Analytics