Skip to content

Commit

Permalink
LC3: lengthOfLongestSubstring: improved
Browse files Browse the repository at this point in the history
  • Loading branch information
davidxifeng committed Jul 23, 2022
1 parent 3f5a98a commit 00788e0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 19 deletions.
5 changes: 4 additions & 1 deletion go/cmd/demo.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,8 @@ func demoMain() {
// fn("bbb", 1)
// fn("abcad", 3)
// fn("pwwkew", 3)
fn("dvdf", 3)
// fn("dvdf", 3)
fn("abb", 2)
fn("abba", 2)
// fn("ddvdf", 3)
}
43 changes: 25 additions & 18 deletions go/demo/leetcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,34 +157,41 @@ func NumToList(n int) *ListNode {
return head
}

func Max(a, b int) int {
if a > b {
return a
} else {
return b
}
}
func Min(a, b int) int {
if a > b {
return b
} else {
return a
}
}

func LengthOfLongestSubstring(s string) int {
sl := utf8.RuneCountInString(s)

vs := []rune(s)

dict := make(map[rune]int)
dict := make(map[rune]int, sl)
count := 0
max := 0

for i := 0; i < sl; {
v := vs[i]

if b, has := dict[v]; has {
count = 0
dict = make(map[rune]int)
i = b + 1
if max > sl-i {
break
}
left := 0
for right := 0; right < sl; right++ {
v := vs[right]
if last, has := dict[v]; has {
count = right - last
left = Max(left, last+1)
dict[v] = right
} else {
dict[v] = i
dict[v] = right
count += 1
i += 1
}

if count > max {
max = count
}
max = Max(max, right-left+1)
}
return max
}
1 change: 1 addition & 0 deletions go/demo/leetcode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,5 @@ func TestLengthOfLongestSubstring(t *testing.T) {
fn("abcabcbb", 3)
fn("pwwkew", 3)
fn("dvdf", 3)
fn("abba", 2)
}

0 comments on commit 00788e0

Please sign in to comment.