30 Substring with Concatenation of All Words

题目链接:https://leetcode.com/problems/substring-with-concatenation-of-all-words/

题目:

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

解题思路
自己想的方法效率比较低。但还是想记录下来。
采取滑动窗口的策略
每次从原字符串取出一个长度为需要匹配的所有单词长度的子串。
这个子串的第一个字符依次为原字符串的第 0 个,第 1 个,第 2 个,以此类推。
把要匹配的单词都放入map中(键为单词本身,值为单词个数),若有重复,值为 2。
将子串切分为需要匹配的单词的个数。
每次从子串中取出一个单词和 map 中的键值匹配
匹配中就从 map 中移除这个单词,没有匹配中就说明该子串不符合要求,跳出本次循环,继续找下一个子串。
若 map 已为空,说明该子串符合要求,用 list 记录下它的起始下标。

public class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> list = new ArrayList();
        if(s == null || words == null || words.length == 0)
            return list;
       HashMap<String, Integer> map = new HashMap();
        for(String word : words) {
            if(map.containsKey(word))
                map.put(word, map.get(word) + 1);
            else
                map.put(word, 1);
        }
        int len = words[0].length();
        int subStringLen = words.length * len;
        for(int k = 0; k <= s.length() - subStringLen; k ++) {
            String subString = s.substring(k, k + subStringLen);
            HashMap<String, Integer> mapTemp = new HashMap(map);
            for(int i = 0; i < words.length; i ++) {
                String word = subString.substring(i * len, (i + 1) * len);
                if(!mapTemp.isEmpty()) {
                    if(mapTemp.containsKey(word)) {
                        if(mapTemp.get(word) == 1)
                            mapTemp.remove(word);
                        else
                            mapTemp.put(word, mapTemp.get(word) - 1);
                    }
                    else
                        break;
                }
                if(mapTemp.isEmpty()) {
                    list.add(k);
                    break;
                }
            }
        }
        return list;
    }
}
169 / 169 test cases passed.
Status: Accepted
Runtime: 836 ms

网上参考:http://blog.csdn.net/linhuanmars/article/details/20342851
方法类似,但执行时间少很多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值