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
}
相关推荐
lly20240626 分钟前
jQuery Mobile 表格
开发语言
惊讶的猫30 分钟前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
m0_748233171 小时前
30秒掌握C++核心精髓
开发语言·c++
Fleshy数模1 小时前
从数据获取到突破限制:Python爬虫进阶实战全攻略
java·开发语言
Duang007_2 小时前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
froginwe112 小时前
Redis 管道技术
开发语言
u0109272712 小时前
C++中的RAII技术深入
开发语言·c++·算法
superman超哥2 小时前
Serde 性能优化的终极武器
开发语言·rust·编程语言·rust serde·serde性能优化·rust开发工具
一个响当当的名号3 小时前
lectrue9 索引并发控制
java·开发语言·数据库
2401_832131953 小时前
模板错误消息优化
开发语言·c++·算法