Skip to content

Commit

Permalink
leetcode 3: string usage in go & a naive answer
Browse files Browse the repository at this point in the history
  • Loading branch information
davidxifeng committed Jul 23, 2022
1 parent 51272b8 commit 3f5a98a
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 5 deletions.
25 changes: 21 additions & 4 deletions go/cmd/demo.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package cmd

import (
"fmt"

"play/demo"
"unicode/utf8"

"github.com/spf13/cobra"
)
Expand All @@ -21,7 +21,24 @@ var demoCmd = &cobra.Command{
}

func demoMain() {
fmt.Println("abs ", demo.AbsIf(-2), demo.AbsBitwise(-2))
fmt.Println("abs ", demo.AbsIf(-9223372036854775808), demo.AbsBitwise(-9223372036854775808))
fmt.Println("abs ", demo.AbsIf(-9223372036854775807), demo.AbsBitwise(9223372036854775807))
s := "中文🏄💾"
for i, v := range s {
fmt.Printf("%d %c %v 0x%05X\n", i, v, v, v)
}
fmt.Println("len s : ", len(s), utf8.RuneCountInString(s))

vs := []rune(s)
fmt.Println(vs)

fn := func(s string, n int) {
if m := demo.LengthOfLongestSubstring(s); m != n {
fmt.Printf("error %s: should be %d, got %d\n", s, n, m)
} else {
fmt.Println("ok", s, n, m)
}
}
// fn("bbb", 1)
// fn("abcad", 3)
// fn("pwwkew", 3)
fn("dvdf", 3)
}
37 changes: 36 additions & 1 deletion go/demo/leetcode.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package demo

import "math/bits"
import (
"math/bits"
"unicode/utf8"
)

func TwoSum(nums []int, target int) []int {
dict := make(map[int]int, len(nums))
Expand Down Expand Up @@ -153,3 +156,35 @@ func NumToList(n int) *ListNode {

return head
}

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

vs := []rune(s)

dict := make(map[rune]int)
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
}
} else {
dict[v] = i
count += 1
i += 1
}

if count > max {
max = count
}
}
return max
}
12 changes: 12 additions & 0 deletions go/demo/leetcode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,15 @@ func TestAddTwoNumbers(t *testing.T) {
testFn(10, 235)
testFn(9999, 2)
}

func TestLengthOfLongestSubstring(t *testing.T) {
fn := func(s string, n int) {
if LengthOfLongestSubstring(s) != n {
t.Fail()
}
}
fn("bbb", 1)
fn("abcabcbb", 3)
fn("pwwkew", 3)
fn("dvdf", 3)
}

0 comments on commit 3f5a98a

Please sign in to comment.