LeetCode题解(Golang实现)--Longest Substring Without Repeating Characters

题目

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

Examples:

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.

简单的来说就是从给予的字符串中计算出没有重复字符串的最长子串的长度

解题思路

最简单的 暴力破解
第二种解题思路是:从字符串中获取一个滑动子串,长度为0,然后遍历字符串,当当前定位的字符不存在与子串中时,则将其放入子串,子串长度加一,并记录最大长度,若已存在,则子串startIndex往前滑动一个位置子串长度减一,并移除第一个字符,然后重复步骤

答案

方案1

func lengthOfLongestSubstring(s string) int {
    max := 0
    for i := 0; i < len(s); i++ {
        for j := i+1; j <= len(s); j++ {
            substr := s[i:j-1]
            if !strings.Contains(substr, s[j-1:j]) {
                if max < j-i {
                    max = j - i
                }
            } else {
                break
            }
        }
    }
    return max
}

方案2

func lengthOfLongestSubstring(s string) int {
    var max,start,end,length = 0,0,0,len(s)
    for start < length && end < length{
        if !strings.Contains(s[start:end],string(s[end])){
            end = end +1
            if end-start > max {
                max = end-start
            }
        }else{
            start = start+1
        }
    }
    return max
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值