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
}
相关推荐
anlogic5 小时前
Java基础 8.18
java·开发语言
沐知全栈开发6 小时前
WebForms XML 文件详解
开发语言
阿巴~阿巴~6 小时前
冒泡排序算法
c语言·开发语言·算法·排序算法
看到我,请让我去学习7 小时前
QT - QT开发进阶合集
开发语言·qt
weixin_307779137 小时前
VS Code配置MinGW64编译SQLite3库
开发语言·数据库·c++·vscode·算法
无聊的小坏坏8 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
励志不掉头发的内向程序员9 小时前
STL库——string(类函数学习)
开发语言·c++
一百天成为python专家9 小时前
Python循环语句 从入门到精通
开发语言·人工智能·python·opencv·支持向量机·计算机视觉
Sunhen_Qiletian9 小时前
朝花夕拾(五)--------Python 中函数、库及接口的详解
开发语言·python
hqwest9 小时前
C#WPF实战出真汁07--【系统设置】--菜品类型设置
开发语言·c#·wpf·grid设计·stackpanel布局