题目描述:对Unix-style的路径进行简化,得到简化的路径
难点:不知道如何简化,要多试用例
解题的思路:对string遍历,./表示当前路径,../表示退回上级目录,///归纳为1个,....等直接复制。还有就是对路径末尾进行处理,不包括/
public class Solution {
public string SimplifyPath(string path) {
List<char> simplifiedPath = new List<char>();
char[] absolutePath = path.ToCharArray();
for (int i = 0; i < absolutePath.Length; i++)
{
if (i <= absolutePath.Length - 1 && absolutePath[i] == '.')
{
if (i==absolutePath.Length-1||absolutePath[i + 1] == '/')
{
i++;
while (i < absolutePath.Length && absolutePath[i] == '/')
{
i++;
}
i--;
}
else if ((i < absolutePath.Length - 2 && absolutePath[i + 1] == '.' && absolutePath[i + 2] == '/') || (i == absolutePath.Length - 2 && absolutePath[i + 1] == '.'))
{
if (simplifiedPath.Count > 1)
simplifiedPath.RemoveAt(simplifiedPath.Count - 1);
int last = simplifiedPath.LastIndexOf('/');
if (last >= 0&&simplifiedPath.Count>=2)
simplifiedPath.RemoveRange(last + 1, simplifiedPath.Count - last - 1);
i += 2;
while (i < absolutePath.Length && absolutePath[i] == '/')
{
i++;
}
i--;
}
else
{
while (i<absolutePath.Length&&absolutePath[i] == '.')
{
simplifiedPath.Add(absolutePath[i]);
i++;
}
i--;
}
}
else if (i < absolutePath.Length - 1 && absolutePath[i] == '/' && absolutePath[i + 1] == '/')
{
simplifiedPath.Add(absolutePath[i]);
while (i < absolutePath.Length && absolutePath[i] == '/')
{
i++;
}
i--;
}
else
simplifiedPath.Add(absolutePath[i]);
}
int k = 0;
for (int i = simplifiedPath.Count - 1; i > 0; i--)
{
if (simplifiedPath[i] != '/' )
{
k = i;
break;
}
}
if (k < simplifiedPath.Count - 1)
simplifiedPath.RemoveRange(k + 1, simplifiedPath.Count - k - 1);
return new string(simplifiedPath.ToArray());
}
}