【LeetCode】 30. Substring with Concatenation of All Words 串联所有单词的子串(Hard)(JAVA)

【LeetCode】 30. Substring with Concatenation of All Words 串联所有单词的子串(Hard)(JAVA)

题目地址: 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.

Example 1:

Input:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
  s = "wordgoodgoodgoodbestword",
  words = ["word","good","best","word"]
Output: []

题目大意

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

解题方法

用一个 Map 把所有的单词存起来,移动位置判断该单词是否在 Map 中。
note:
1、words 可能是重复的,存入 Map 的时候要计算次数。
2、words 里面的单词长度都是相同的,只要每次移动 word.length() 然后判断是否在 words 里即可。

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> res = new ArrayList<>();
        
        if (words.length == 0 || words[0].length() == 0 || s.length() < words[0].length() * words.length) return res;
        int len = words[0].length();
        int allLen = len * words.length;
        Map<String, Integer> origin = new HashMap<>();
        Map<String, Integer> cur;
        for (int i = 0; i < words.length; i++) {
            Integer temp = origin.get(words[i]);
            if (temp == null) {
                origin.put(words[i], 1);
            } else {
                origin.put(words[i], temp + 1);
            }
            
        }
        for (int i = 0; i <= s.length() - allLen; i++) {
            if (origin.get(s.substring(i, i + len)) == null) continue;
            cur = new HashMap<>(origin);
            int j = 0;
            for (; j < words.length; j++) {
                String temp = s.substring(i + len * j, i + len * (j + 1));
                Integer count = cur.get(temp);
                if (count == null || count <= 0) break;
                cur.put(temp, count - 1);
            }
            if (j >= words.length) res.add(i);
        }
        return res;
    }
}

执行用时 : 146 ms, 在所有 Java 提交中击败了 39.26% 的用户
内存消耗 : 41.8 MB, 在所有 Java 提交中击败了 16.49% 的用户

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值