码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Substring with Concatenation of All Words

时间:2015-05-16 16:32:19      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:leetcode

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in wordsexactly once and without any intervening characters.

For example, given:
s"barfoothefoobarman"
words["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

思路:
利用两个数据结构toFind ,hasFound分别表示需要找的字符串和已经查找到的字符串
然后遍历s,如果能够按 words[0].length为步长查找 words.length 步满足 toFind 和 hasFound 一致的话
则表示查找到一个满足的组合
代码:

    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> rs = new LinkedList<Integer>();

        Map<String, Integer> toFind = new HashMap<String, Integer>();
        Map<String, Integer> hasFound = new HashMap<String, Integer>();

        for (int i = 0; i< words.length; ++i){//去重
            if(toFind.get(words[i]) == null){
                toFind.put(words[i], 1);
            }else {
                toFind.put(words[i], toFind.get(words[i]) + 1);
            }

        }

        int wordsCount = words.length;
        int step = words[0].length();
        int loop = s.length() - wordsCount * step;//循环查找的次数

        for(int i = 0; i <= loop; ++ i){//外层循环保遍历所有可能的顺序字符串
            hasFound.clear();
            int j =0;
            for(; j < wordsCount; ++j){
                int k = i + j * step;//以step为单元
                String sub = s.substring(k, k + step);
                if(! toFind.containsKey(sub)) break;
                if(hasFound.containsKey(sub)){
                    hasFound.put(sub, hasFound.get(sub) + 1);
                }else {
                    hasFound.put(sub, 1);
                }
                if(hasFound.get(sub) > toFind.get(sub)) break;
            }
            if(j == wordsCount) rs.add(i);
        }


        return rs;
    }


[LeetCode]Substring with Concatenation of All Words

标签:leetcode

原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/45768859

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!