Skip to content

Commit 4a8b2ed

Browse files
authored
Merge pull request #7 from ansidev/content/add
Content: add LeetCode solution for problems 3, 8, 53, 231, 628, 2400
2 parents 66dca5b + 5b93e23 commit 4a8b2ed

6 files changed

+824
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
---
2+
layout: "../layouts/Post.astro"
3+
title: "3. Longest Substring Without Repeating Characters"
4+
slug: "0003-longest-substring-without-repeating-characters"
5+
keywords:
6+
- "longest"
7+
- "substring"
8+
- "without"
9+
- "repeating"
10+
- "characters"
11+
author: "ansidev"
12+
pubDate: "2022-10-31T19:46:49+07:00"
13+
difficulty: "Medium"
14+
tags:
15+
- "Hash Table"
16+
- "String"
17+
- "Sliding Window"
18+
---
19+
## Problem
20+
21+
Given a string `s`, find the length of the **longest substring** without repeating characters.
22+
23+
**Example 1:**
24+
25+
```
26+
Input: s = "abcabcbb"
27+
Output: 3
28+
Explanation: The answer is "abc", with the length of 3.
29+
```
30+
31+
**Example 2:**
32+
33+
```
34+
Input: s = "bbbbb"
35+
Output: 1
36+
Explanation: The answer is "b", with the length of 1.
37+
```
38+
39+
**Example 3:**
40+
41+
```
42+
Input: s = "pwwkew"
43+
Output: 3
44+
Explanation: The answer is "wke", with the length of 3.
45+
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
46+
```
47+
48+
**Constraints:**
49+
50+
- `0 <= s.length <= 5 * 104`
51+
- `s` consists of English letters, digits, symbols, and spaces.
52+
53+
## Analysis
54+
55+
| Abbreviation | Stands for |
56+
| ------------ | ------------------------------------------------ |
57+
| `CSWRC` | `current substring without repeating characters` |
58+
| `LSWRC` | `longest substring without repeating characters` |
59+
60+
- If `s` is an empty string, the LSWRC is `0`.
61+
- If the length of string `s` is 1, the LSWRC is `1`.
62+
63+
## Approaches
64+
65+
### Approach 1
66+
67+
#### Approach
68+
69+
- If the length of string `s` is greater than 1, because we need to determine the LSWRC, while iterating over the string, we have to check whether the character at a specific index is repeating or not. We can consider using a hashmap.
70+
71+
- Assume the `LSWRC` is `s[0]`.
72+
73+
| Initial value | Note |
74+
| --------------------- | ---------------------------------------------------------------------- |
75+
| `left = 0` | Left index of the LSWRC |
76+
| `result = 1` | Length of the LSWRC |
77+
| `lastIndex = { a=0 }` | This hashmap saves the last index of a specific character of the array |
78+
79+
- Start traversing the array from index `1`. For each step:
80+
- Check whether the current character is repeating: `lastIndex` has the key `s[right]`.
81+
- If yes, update `left = lastIndex[s[right]] + 1` if `left < lastIndex[s[right]] + 1`.
82+
- Update the last index of `s[right]` to the current index.
83+
- Calculate the new length of the `CSWRC`. (`right - left + 1`).
84+
- Update `result` if it is less than the new length of the `CSWRC`.
85+
- Finally, return `result`. It is the `LSWRC`.
86+
87+
#### Solutions
88+
89+
```go
90+
func lengthOfLongestSubstring(s string) int {
91+
l := len(s)
92+
if l == 0 || l == 1 {
93+
return l
94+
}
95+
96+
result, left := 1, 0
97+
lastIndex := map[byte]int{}
98+
lastIndex[s[0]] = 0
99+
for right := 1; right < l; right++ {
100+
if v, ok := lastIndex[s[right]]; ok {
101+
if left < v+1 {
102+
left = v + 1
103+
}
104+
}
105+
lastIndex[s[right]] = right
106+
if result < right-left+1 {
107+
result = right - left + 1
108+
}
109+
}
110+
111+
return result
112+
}
113+
```
114+
115+
#### Complexity
116+
117+
- Time complexity: `O(n)` because we just traverse the string once.
118+
- Space complexity:
119+
- We use four extra variables `l`, `result`, `left`, `right`, no matter what value will, they will take fixed bytes. So the space complexity is `O(1)`.
120+
- The space complexity of the map `lastIndex` is `O(n)`.
121+
- So the final space complexity is `O(n)`.
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
---
2+
layout: "../layouts/Post.astro"
3+
title: "8. String to Integer (atoi)"
4+
slug: "0008-string-to-integer-atoi"
5+
keywords:
6+
- "string"
7+
- "to"
8+
- "integer"
9+
- "atoi"
10+
author: "ansidev"
11+
pubDate: "2022-10-26T13:11:00+07:00"
12+
difficulty: "Medium"
13+
tags:
14+
- "String"
15+
---
16+
## Problem
17+
18+
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function).
19+
20+
The algorithm for `myAtoi(string s)` is as follows:
21+
22+
1. Read in and ignore any leading whitespace.
23+
2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
24+
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
25+
4. Convert these digits into an integer (i.e. `"123" -> 123`, `"0032" -> 32`). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
26+
5. If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then clamp the integer so that it remains in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be clamped to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup>-1</code> should be clamped to <code>2<sup>31</sup>-1</code>.
27+
Return the integer as the final result.
28+
29+
**Note:**
30+
31+
- Only the space character `' '` is considered a whitespace character.
32+
- **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits.
33+
34+
**Example 1:**
35+
36+
```
37+
Input: s = "42"
38+
Output: 42
39+
Explanation: The underlined characters are what is read in, the caret is the current reader position.
40+
Step 1: "42" (no characters read because there is no leading whitespace)
41+
^
42+
Step 2: "42" (no characters read because there is neither a `'-'` nor `'+'`)
43+
^
44+
Step 3: "42" ("42" is read in)
45+
^
46+
The parsed integer is 42.
47+
Since 42 is in the range [-2^31, 2^31 - 1], the final result is 42.
48+
```
49+
50+
**Example 2:**
51+
52+
```
53+
Input: s = " -42"
54+
Output: -42
55+
Explanation:
56+
Step 1: " -42" (leading whitespace is read and ignored)
57+
^
58+
Step 2: " -42" (`'-'` is read, so the result should be negative)
59+
^
60+
Step 3: " -42" ("42" is read in)
61+
^
62+
The parsed integer is -42.
63+
Since -42 is in the range [-2^31, 2^31 - 1], the final result is -42.
64+
```
65+
66+
**Example 3:**
67+
68+
```
69+
Input: s = "4193 with words"
70+
Output: 4193
71+
Explanation:
72+
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
73+
^
74+
Step 2: "4193 with words" (no characters read because there is neither a `'-'` nor `'+'`)
75+
^
76+
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
77+
^
78+
The parsed integer is 4193.
79+
Since 4193 is in the range [-2^31, 2^31 - 1], the final result is 4193.
80+
```
81+
82+
**Constraints:**
83+
84+
- `0 <= s.length <= 200`.
85+
- `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
86+
87+
## Analysis
88+
89+
I don't have any special analysis since the problem is so clearly.
90+
91+
## Approaches
92+
93+
### Approach 1
94+
95+
#### Approach
96+
97+
1. Check whether the input is null (depends on programming language) or empty. If it is, return `0`.
98+
2. Use a pointer `i` to traverse the input string, always remember checking whether i less than length of `s`.
99+
- While `s[i]` is a whitespace, keep increasing i by 1.
100+
- Check whether the next character (`s[i]`) is one of `-`, `+`, or digit (`0-9`):
101+
- If not, return `0`.
102+
- Otherwise, check whether `s[i]` is one of `-` or `+`, save the result to a boolean variable and increase i by 1.
103+
- Note that if `s[i]` is not one of `-` or `+`, this means that it is a digit, and `i` will not be increased.
104+
- Check whether the current character is a sign, if it is, return `0` because it is an invalid input.
105+
- Create new 64 bit float number `n` to save the result.
106+
- While `s[i]` is a digit, `n = n x 10 + integer value of s[i]`, then increasing `i` by `1`.
107+
- If the sign is `-`, `n = -n`.
108+
- Check the range of `n`:
109+
- If <code>n < -2<sup>31</sup></code>, return <code>-2<sup>31</sup></code>.
110+
- If <code>n > 2<sup>31</sup>-1</code>, return <code>2<sup>31</sup>-1</code>.
111+
- Otherwise, convert n to integer and return.
112+
113+
- Notes: `MinInt32 = -1 << 31` (<code>-2<sup>31</sup></code>) and `MaxInt32 = 1<<31 - 1` (<code>2<sup>31</sup>-1</code>).
114+
115+
#### Solutions
116+
117+
```go
118+
func myAtoi(s string) int {
119+
l := len(s)
120+
if l == 0 {
121+
return 0
122+
}
123+
124+
i := 0
125+
for i < l && s[i] == ' ' {
126+
i++
127+
}
128+
129+
if i < l && s[i] != '+' &&
130+
s[i] != '-' &&
131+
s[i] != '0' &&
132+
s[i] != '1' &&
133+
s[i] != '2' &&
134+
s[i] != '3' &&
135+
s[i] != '4' &&
136+
s[i] != '5' &&
137+
s[i] != '6' &&
138+
s[i] != '7' &&
139+
s[i] != '8' &&
140+
s[i] != '9' {
141+
return 0
142+
}
143+
144+
isNegative := false
145+
if i < l && s[i] == '-' {
146+
isNegative = true
147+
i++
148+
} else if i < l && s[i] == '+' {
149+
i++
150+
}
151+
152+
if i < l && (s[i] == '+' || s[i] == '-') {
153+
return 0
154+
}
155+
156+
var n float64 = 0
157+
for i < l && s[i] >= '0' && s[i] <= '9' {
158+
n = n*10 + float64(s[i]-'0')
159+
i++
160+
}
161+
162+
if isNegative {
163+
n = -n
164+
}
165+
166+
if n < math.MinInt32 {
167+
return math.MinInt32
168+
}
169+
if n > math.MaxInt32 {
170+
return math.MaxInt32
171+
}
172+
173+
return int(n)
174+
}
175+
```
176+
177+
#### Complexity
178+
179+
- Time complexity: `O(n)` because we just traverse the string once.
180+
- Space complexity: We use three extra variable `l`, `isNegative`, `n`, no matter what value will, they will take a fixed bytes. So the space complexity is `O(1)`.

0 commit comments

Comments
 (0)