-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongestchar.go
37 lines (31 loc) · 944 Bytes
/
longestchar.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Source: https://leetcode.com/problems/longest-substring-without-repeating-characters/
// Author: Lin Tanghui
// Date : 2015/10/31
// Given a string, find the length of the longest substring without repeating characters.
// For example, the longest substring without repeating letters
// for "abcabcbb" is "abc", which the length is 3.
// For "bbbbb" the longest substring is "b", with the length of 1.
package lenthofsubstring
func lengthOfLongestSubstring(s string) int {
if s == "" {
return 0
}
var (
substring map[rune]int = make(map[rune]int, 0)
m, longest, num int
)
for index, ch := range s {
num, _ = substring[ch]
m = max(num, m)
substring[ch] = index // update index when has the same num
longest = max(longest, index-m)
}
return longest
}
func max(a, b int) int {
if a < b {
return b
} else {
return a
}
}