简化路径目录问题与堆栈



我需要实现一个函数来简化目录的路径,例如"/home//foo/"需要"/home/foo",我需要删除所有重复的斜杠,但它删除了所有的斜杠在这个,我如何使它删除所有重复和尾斜杠?

注意这个堆栈是由我使用链表方法实现的,它只有(pop和push, get top, isEmpty和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;

}

嗯,这段代码有点夸张了。您应该使用STL的功能,如果您这样做,那么您可以在一行代码中删除所有重复的斜杠(为简洁起见,我将变量称为s):

s.erase (std::unique (s.begin (), s.end (), [] (char a, char b) { return a == b && a == '/'; }), s.end ());

然后检查是否有尾斜杠并删除它就很简单了。我把那部分留给你。

现场演示。

文档:

std::unique
std::string::erase

最新更新