'Simplify Path directory problem with stack
I need to implement a function to simplify the path of a directory for example "/home//foo/" need to be "/home/foo", i need to delete all the duplicate slashes but it removes all the slashes in this one, how do i make it remove all the duplicates and the trailing slash?
note this stack is implemented by me using linked list approach it only has (pop and push, get top, isEmpty, and size)
string simplify(string A)
{
// stack to store the file's names.
Stack<string> st;
string dir;
string res;
// every string starts from root directory.
res.append("/");
int len_A = A.length();
for (int i = 0; i < len_A; i++) {
dir.clear();
//the problem is here
while (A[i] =='/')
i++;
while (i < len_A && A[i] != '/') {
dir.push_back(A[i]);
i++;
}
if (dir.compare("..") == 0) {
if (!st.isEmpty())
st.pop();
}
else if (dir.compare(".") == 0)
continue;
else if (dir.length() != 0)
st.push(dir);
}
Stack<string> st1;
while (!st.isEmpty()) {
string x = "";
st.getTop(x);
st1.push(x);
st.pop();
}
// the st1 will contain the actual res.
while (!st1.isEmpty()) {
string temp = st1.getTop();
// if it's the last element no need
// to append "/"
if (st1.size() != 1)
{res.append(temp);}
st1.pop();
}
return res;
}
Solution 1:[1]
Hmmm, that code is a little overblown. You should use the power of the STL, and if you do that then you can remove all the duplicate slashes in a single line of code (I'm calling my variable s for brevity):
s.erase (std::unique (s.begin (), s.end (), [] (char a, char b) { return a == b && a == '/'; }), s.end ());
It is then trivial to check for a trailing slash and remove it if you find one. I'll leave that bit to you.
Documentation:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul Sanders |
