File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments