Interview Questions

267. Given a directory path find the most optimum traversal.

Microsoft Interview Questions and Answers


(Continued from previous question...)

267. Given a directory path find the most optimum traversal.

Question:

Given a directory path find the most optimum traversal.
eg: \a\c\..\d => \a\d
\a\b\c\..\..\d\.. => \a
etc



maybe an answer:


/// <summary>
/// Given a directory path find the most optimum traversal. e.g. \a\c\..\d => \a\d

/// </summary>
[TestMethod]
public void DirectoryPath()
{
StringBuilder path = new StringBuilder(@"\a\b\c\..\d\e\..\f\..\g");


if (string.IsNullOrEmpty(path.ToString()))
{
return;
}

int insertIndex = path.Length - 1;
int scanIndex = insertIndex;
int parentCount = 0;

while (scanIndex > 0)
{
if ((path[scanIndex] == '.') && (path[scanIndex - 1] == '.'))
{
parentCount++;
scanIndex -= 3; // Skip two . and \
}
else
{
if (parentCount > 0)
{
scanIndex -= 2; // Skip the character and \
parentCount--;
}
else
{
path[insertIndex--] = path[scanIndex];
path[insertIndex--] = '\\'; // Copy the character and \
scanIndex -= 2;
}
}
}


StringBuilder builder = new StringBuilder();
while (++insertIndex < path.Length)
{
builder.Append(path[insertIndex]);
}


string result = builder.ToString();
}

(Continued on next question...)

Other Interview Questions