-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSolution.kt
54 lines (50 loc) · 1.39 KB
/
Solution.kt
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Created by Inno Fang on 2018/3/2.
*/
/**
* 252 / 252 test cases passed.
* Status: Accepted
* Runtime: 348 ms
*/
class Solution {
fun simplifyPath(path: String): String {
if (path.isEmpty()) return path
val stack = mutableListOf<String>()
path.split("/").let {
it.slice(1..it.lastIndex).forEach {
when (it) {
".", "" -> return@forEach
"" -> if (stack.isNotEmpty()) stack.removeAt(stack.lastIndex)
else -> if (it.isNotEmpty()) stack.add("/$it")
}
}
}
if (stack.isEmpty()) stack.add("/")
return stack.joinToString("")
}
}
fun main(args: Array<String>) {
Solution().simplifyPath("/home/").let(::println)
Solution().simplifyPath("/a/./b/../../c/").let(::println)
Solution().simplifyPath("/a/..").let(::println)
Solution().simplifyPath("/").let(::println)
Solution().simplifyPath("/.").let(::println)
Solution().simplifyPath("/home/foo/.ssh/../.ssh2/authorized_keys/").let(::println)
Solution().simplifyPath("").let(::println)
Solution().simplifyPath("///TJbrd/owxdG//").let(::println)
}
// more testcase
/*
"/"
""
"/home/foo/.ssh/../.ssh2/authorized_keys/"
"/."
"/.."
"/home/"
"/home/."
"/home/.."
"/a/./b/../../c/"
"/../"
"/home//foo/"
"///TJbrd/owxdG//"
*/