加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 18:06:46 所属栏目:大数据 来源:网络整理
导读:题目 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

题目

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,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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读