首页 > 其他 > 详细

Substring with Concatenation of All Words

时间:2015-06-07 02:05:07      阅读:263      评论:0      收藏:0      [点我收藏+]

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).

题目意思: 输入字符串S和列表L,L含有一组长度相同的单词。找出所有子串的开始下标,该子串由L的所有单词拼接而成,而且没有夹杂其他字符

?

public class Solution {
    public List<Integer> findSubstring(String S, String[] L) {
        Map<String, Integer> dict = new HashMap<String, Integer>();
        for (String l : L) {
            if (!dict.containsKey(l)) {
                dict.put(l, 0);
            }
            dict.put(l, dict.get(l)+1);
        }
         
        int len = L[0].length();
        int lenSum = len*L.length;
         
        List<Integer> list = new ArrayList<Integer>();
         
        for (int i=0; i<=S.length()-lenSum; i++) {
            Map<String, Integer> dictCopy = new HashMap<String, Integer>(dict);
            boolean flag = true; 
            for (int j=i; j<i+lenSum; j=j+len) {
                String s = S.substring(j, j+len);
                Integer num = dictCopy.get(s);
                if (num==null || num==0) {
                	flag = false;
                	break;
                }
                num--;
                dictCopy.put(s, num);
            }
            if (flag) {
            	list.add(i);
            }
        }
         
        return list;
    }
}

?

Substring with Concatenation of All Words

原文:http://hcx2013.iteye.com/blog/2217608

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!