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

被折叠的 条评论
为什么被折叠?



