GoLang刷题之leetcode

题目30:串联所有单词的子串

题目描述:

给定一个字符串 s 和一个字符串数组 words。 words 中所有字符串 长度相同。

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

例如,如果 words = ["ab","cd","ef"], 那么 "abcdef", "abefcd","cdabef", "cdefab","efabcd", 和 "efcdab" 都是串联子串。 "acdbef" 不是串联子串,因为他不是任何 words 排列的连接。

返回所有串联子串在 s 中的开始索引。你可以以 任意顺序 返回答案。

题解:

go 复制代码
func findSubstring(s string, words []string) []int {
    res := []int{}
    sl := len(s)                   //字符串长度
    wl := len(words[0])         //words单个字符串长度
    wsl := wl * len(words)   //words总长度
    if sl < wsl{
        return res
    }
    countmap := make(map[string]int) //存放words中各字符串出现次数
    for _, w := range words{
        countmap[w]++
    }
    for i:=0;i<=sl - wsl;i++{
        tmp := make(map[string]int)
        for _, w1 := range words{
            tmp[w1]++
        }
        num := 0 //记录某个字符串已经出现的次数
        for num < len(words){
            word := s[i+num*wl:i+(num+1)*wl]
            _,wordcount := tmp[word]
             if wordcount{
                tmp[word]--
                if tmp[word]<0{
                    break
                }
            }else{
                break
            }
            num++
        }
        if num == len(words){
            res = append(res,i)
        }
       
    }
    return res
}
相关推荐
Dream it possible!18 小时前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi18 小时前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
6***379418 小时前
Java安全
java·开发语言·安全
豐儀麟阁贵18 小时前
8.1 异常概述
java·开发语言
czhc114007566319 小时前
C# 1124 接收
开发语言·c#
司铭鸿20 小时前
祖先关系的数学重构:从家谱到算法的思维跃迁
开发语言·数据结构·人工智能·算法·重构·c#·哈希算法
wavemap20 小时前
先到先得:免费订阅一年ChatGPT Go会员
开发语言·chatgpt·golang
m***D28621 小时前
JavaScript在Node.js中的内存管理
开发语言·javascript·node.js
我叫张小白。21 小时前
JavaScript现代语法梳理:ES6+核心特性详解
开发语言·javascript·typescript·es6
-森屿安年-21 小时前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode