Longest Substring Without Repeating Characters(Time Limit Exceeded)

本文探讨了如何找出给定字符串中最长的无重复字符子串,并提供了两种Go语言实现方案,一种超时,另一种被接受。通过对比两种方法,读者可以了解如何优化算法以提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

Given a string, find the length of the  longest substring  without repeating characters.


测试用例

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.



我的代码(Time Limit Exceeded)

func lengthOfLongestSubstring(s string) int {
    var maxLength int
    var tmpString string
    maxLength = 0
    
    lengthOfString := len(s)
    //fmt.Println(lengthOfString)
    
    for i := 0; i < lengthOfString; i++{
        for j:= i + 1; j <= lengthOfString; j++{
            if j == lengthOfString {
                tmpString = s[i : ]
            }else{
                tmpString = s[i : j]
            }
            //fmt.Println(tmpString, j - i)
            if checkRepeatingChar(tmpString) && (j - i) > maxLength{
                maxLength = j - i
            }
        }
    }
    
    return maxLength
}

func checkRepeatingChar(s string) bool{
    referenceOfs := s
    
    for i := 0; i < len(s); i++{
        for j := 0; j < len(s); j++{
            //fmt.Println(s[i], referenceOfs[j])
            if i == j {
                continue
            }else if s[i] == referenceOfs[j]{
                return false
            }
        }
    }
    
    return true
}



我的代码(Accepted)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值