Solution:
Problem:
class Solution {
public:
void split(string str, vector<string>& folders, char dil) {
stringstream ss(str);
string split_str;
while (getline(ss, split_str, dil)) {
folders.push_back(split_str);
}
return;
}
string simplifyPath(string path) {
stack<string> st;
vector<string> folders;
split(path, folders, '/');
for (int i = 0; i < folders.size(); i++) {
if (folders[i] == "..") {
if(!st.empty()) {
st.pop();
}
} else if (folders[i] != "." && folders[i] != "") {
st.push(folders[i]);
}
}
string ans;
while (!st.empty()) {
ans = "/" + st.top() + ans;
st.pop();
}
return (ans.empty() ? "/": ans);
}
};
============= Updated ========
class Solution {
public:
vector<string> split(string str, char delim) {
vector<string> ans;
stringstream ss(str);
string token;
while(getline(ss, token, delim)) {
ans.push_back(token);
}
return ans;
}
string form_ans(stack<string> st) {
string ans;
while (!st.empty()) {
ans = st.top() + ans;
ans = "/" + ans;
st.pop();
}
if (ans == "") {
return "/";
}
return ans;
}
string simplifyPath(string path) {
stack<string> st;
vector<string> strs = split(path, '/');
for (int i = 0; i < strs.size(); i++) {
if (strs[i] != ".." && strs[i] != "." && strs[i] != "") {
st.push(strs[i]);
} else if (strs[i] == "..") {
if (!st.empty()) {
st.pop();
}
}
}
string ans = form_ans(st);
return ans;
}
};
Problem:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
path =
"/home/"
, => "/home"
path =
"/a/./b/../../c/"
, => "/c"
class Solution {
public:
void split(string str, vector<string>& folders, char dil) {
stringstream ss(str);
string split_str;
while (getline(ss, split_str, dil)) {
folders.push_back(split_str);
}
return;
}
string simplifyPath(string path) {
stack<string> st;
vector<string> folders;
split(path, folders, '/');
for (int i = 0; i < folders.size(); i++) {
if (folders[i] == "..") {
if(!st.empty()) {
st.pop();
}
} else if (folders[i] != "." && folders[i] != "") {
st.push(folders[i]);
}
}
string ans;
while (!st.empty()) {
ans = "/" + st.top() + ans;
st.pop();
}
return (ans.empty() ? "/": ans);
}
};
============= Updated ========
class Solution {
public:
vector<string> split(string str, char delim) {
vector<string> ans;
stringstream ss(str);
string token;
while(getline(ss, token, delim)) {
ans.push_back(token);
}
return ans;
}
string form_ans(stack<string> st) {
string ans;
while (!st.empty()) {
ans = st.top() + ans;
ans = "/" + ans;
st.pop();
}
if (ans == "") {
return "/";
}
return ans;
}
string simplifyPath(string path) {
stack<string> st;
vector<string> strs = split(path, '/');
for (int i = 0; i < strs.size(); i++) {
if (strs[i] != ".." && strs[i] != "." && strs[i] != "") {
st.push(strs[i]);
} else if (strs[i] == "..") {
if (!st.empty()) {
st.pop();
}
}
}
string ans = form_ans(st);
return ans;
}
};
No comments:
Post a Comment