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
}
相关推荐
冷雨夜中漫步1 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
m0_736919103 小时前
C++代码风格检查工具
开发语言·c++·算法
2501_944934733 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
黎雁·泠崖4 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472465 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
TechWJ5 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
lly2024066 小时前
C++ 文件和流
开发语言
m0_706653236 小时前
分布式系统安全通信
开发语言·c++·算法
2501_941982056 小时前
深度对比:Java、Go、Python 实现企微外部群推送,哪个效率更高?
java·golang·企业微信
寻寻觅觅☆6 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++