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
}
相关推荐
aramae1 小时前
模拟实现strcmp()(C语言)
c语言·开发语言·后端
泡海椒2 小时前
PDF 表格样式优化:jquick-pdf 边框、圆角、背景色
java·开发语言·pdf
Beyond_System|系统之外3 小时前
【学编程】Python基础编程题100道(21-60)
开发语言·python·算法
景熙55234 小时前
15.Java 8 Stream 流入门到实战
java·开发语言·数据结构
圣保罗的大教堂5 小时前
leetcode 835. 图像重叠 中等
leetcode
Bruce_Liuxiaowei6 小时前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
aramae7 小时前
MySQL内置函数(7)
开发语言·笔记·后端·mysql·其他
五彩小白8 小时前
GO语言装饰器语法
golang
wabs6669 小时前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
hanlin039 小时前
刷题笔记:力扣第41题-缺失的第一个正数
笔记·算法·leetcode