2016年12月15日 星期四

[LeetCode] 71. Simplify Path

轉自 LeetCode

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".
<Solution>

這題是要去找出最後最精簡的 path

可以看到 input 是用 '/ ' 來做切分

因此,可以使用 stringstream 來幫忙做這件事

利用 stringstream 將兩個 / 之間的字串給取出來後,可能有以下情況
  • 空字串 : 例如 "//"
  • "." : 代表當下位置,沒有移動
  • ".." : 到上一層
  • 其餘就是檔案或是目錄名稱
這邊附上一些測資

"/"
"/../"
"/home//file"
"/home/"
"/a/./b/../../c/"
"/..."
"/."
"/..hidden"
"/.hidden"
"/home/foo/.ssh/authorized_keys/"

code 如下
c++
class Solution {
public:
string simplifyPath(string path) {
string tmpStr;
stringstream ss(path);
vector<string> token;
while(getline(ss, tmpStr, '/')) {
if(tmpStr == "" || tmpStr == ".") {
continue;
}
if(tmpStr == ".." && !token.empty()) {
token.pop_back();
}
else if(tmpStr != "..") {
token.push_back(tmpStr);
}
}
//> combine string in reverse order
string ans;
for(auto s : token) {
ans += "/" + s;
}
return (token.empty()) ? "/" : ans;
}
};

kotlin
class Solution {
fun simplifyPath(path: String): String {
val paths = path.split("/")
val tokens = mutableListOf<String>()
loop@ for(p in paths) {
when {
p.isBlank() || p == "." -> continue@loop
p == ".." && tokens.isNotEmpty() -> tokens.removeAt(tokens.lastIndex)
p != ".." -> tokens.add(p)
}
}
return if (tokens.isEmpty()) {
"/"
} else {
val sb = StringBuilder()
for(t in tokens) {
sb.append("/$t")
}
sb.toString()
}
}
}

沒有留言:

張貼留言