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

[leetcode] Substring with Concatenation of All Words

时间:2014-12-31 06:16:33      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

题目:(HashTable,Two Point)

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

For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]

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

 

题解:

看代码思路还是很清晰的就是顺着给的string s,找。不过不是找一个字母,而是找一个单词,然后L里面的所有单词又刚好都要来一遍。

public class Solution {
    public ArrayList<Integer> findSubstring(String S, String[] L) {
        HashMap<String, Integer> Lmap = new HashMap<String, Integer>();
        HashMap<String, Integer> Smap = new HashMap<String, Integer>();
        ArrayList<Integer> result = new ArrayList<Integer>();
        int total = L.length;
        if(total==0)
        return result;
        
        for(int i=0;i<total;i++)
        {
            if(!Lmap.containsKey(L[i]))
                 Lmap.put(L[i], 1);
            else
            {
                int k = Lmap.get(L[i]);
                Lmap.put(L[i], k+1);
            }
        }
        
        int len = L[0].length();
        for(int i=0;i<=S.length()-len*total;i++)
        {
            Smap.clear();
            int j = 0;
            for(;j<total;j++)
            {
                String s = S.substring(i+j*len, i+(j+1)*len);
                if(!Lmap.containsKey(s))
                    break;
                    
                if(!Smap.containsKey(s))
                    Smap.put(s, 1);
                else
                {
                    int k = Smap.get(s);
                    Smap.put(s, k+1);
                }
                if(Smap.get(s)>Lmap.get(s))
                    break;
            }
            if(j==total)
            {
                result.add(i);
            }
        }
        return result;
    }
}

 

[leetcode] Substring with Concatenation of All Words

标签:

原文地址:http://www.cnblogs.com/fengmangZoo/p/4194923.html

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