![]() |
VOOZH | about |
Given n directory paths, we need to write a program to find longest common directory path.
Examples:
Input : 3
"/home/User/Desktop/gfg/test"
"/home/User/Desktop/gfg/file"
"/home/User/Desktop/geeks/folders"
Output : Longest Common Path is /home/User/Desktop!
Input : 4
"/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/gfg/folders",
"/home/User/Desktop/gfg/folders"
Output : Longest Common Path is /home/User/Desktop/gfg!
In the function LongestCommonPath() there are two main variables used which are "CommonCharacters" for storing the length of common characters and "CommonString" for storing the longest string of paths so that we get our longest common path.
CommonCharacter variable gets updated in each iteration depending upon the length of common path appearing in the input paths.
Lastly, we get the length of common path string after the iteration. Then, we get our common path by the substring till the separator '/' as if we don't do this then we get the longest common string among the paths, which should not be our result .
Below is the implementation of the above approach .
Longest Common Path is /home/User/Desktop/gfg!