Skip to content

Commit 44ecbbd

Browse files
committed
add algorithm class LongetSubstring by GyooHa
1 parent 00c86e6 commit 44ecbbd

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
2+
import kotlin.system.measureTimeMillis
3+
/*Example 1:
4+
Input: "abcabcbb"
5+
Output: 3
6+
Explanation: The answer is "abc", with the length of 3.
7+
Example 2:
8+
Input: "bbbbb"
9+
Output: 1
10+
Explanation: The answer is "b", with the length of 1.
11+
Example 3:
12+
Input: "pwwkew"
13+
Output: 3
14+
Explanation: The answer is "wke", with the length of 3.
15+
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.*/
16+
class Solution2 {
17+
fun lengthOfLongestSubstring(s: String): Int = if (s.length <= 1) s.length else recursive(s).length
18+
private tailrec fun recursive(
19+
s: String,
20+
acc: String = ""
21+
): String = when {
22+
s.isEmpty() -> acc
23+
else -> {
24+
val tail = s.drop(1)
25+
val recursiveAcc = recursive2(s)
26+
val greaterThan = acc.length > recursiveAcc.length
27+
val result = if (greaterThan) acc else recursiveAcc
28+
recursive(
29+
tail,
30+
result
31+
)
32+
}
33+
}
34+
private tailrec fun recursive2(
35+
s: String,
36+
acc: String = ""
37+
): String = when {
38+
s.isEmpty() -> acc
39+
else -> {
40+
val head = s[0]
41+
val tail = s.drop(1)
42+
when {
43+
acc.contains(head) -> acc
44+
else -> recursive2(tail, acc + head)
45+
}
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)