leetcode-30. 串联所有单词的子串

文章讨论了如何利用Java编写Solution类的方法findSubstring,寻找给定字符串s中,由给定单词数组words组成的串联子串的起始索引。hit方法用于检查特定子串是否符合要求。
摘要由CSDN通过智能技术生成
https://leetcode.cn/problems/substring-with-concatenation-of-all-words/description/?envType=study-plan-v2&envId=top-interview-150
给定一个字符串 s 和一个字符串数组 words。 words 中所有字符串 长度相同。

 s 中的 串联子串 是指一个包含  words 中所有字符串以任意顺序排列连接起来的子串。

例如,如果 words = ["ab","cd","ef"], 那么 "abcdef", "abefcd","cdabef", "cdefab","efabcd", 和 "efcdab" 都是串联子串。 "acdbef" 不是串联子串,因为他不是任何 words 排列的连接。
返回所有串联子串在 s 中的开始索引。你可以以 任意顺序 返回答案。
class Solution {

    public List<Integer> findSubstring(String s, String[] words) {
        int len = 0;
        Map<String, AtomicInteger> wordMap = new HashMap<>();
        for (String word : words) {
            len += word.length();
            wordMap.computeIfAbsent(word, it -> new AtomicInteger()).getAndIncrement();
        }
        List<Integer> res = new ArrayList<>();
        if (s.length() < len) {
            return res;
        }

        int wordLen = words[0].length();
        for (int i = 0; i + len <= s.length(); i++) {
            if (hit(s, i, len, wordLen, wordMap)) {
                res.add(i);
            }
        }
        return res;
    }

    private boolean hit(String s, int pos, int len, int wordLen, Map<String, AtomicInteger> wordMap) {
        Map<String, AtomicInteger> map = new HashMap<>();
        for (int i = 0; i < len;) {
            map.computeIfAbsent(
                    s.substring(pos+i, pos+i+wordLen),
                   it -> new AtomicInteger()
            ).getAndIncrement();
            i+= wordLen;
        }

        for (Map.Entry<String, AtomicInteger> entry : wordMap.entrySet()) {
            AtomicInteger now = map.get(entry.getKey());
            if (null == now || now.get() < entry.getValue().get()) {
                return false;
            }
        }
        return true;
    }
}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值