最长公共目录路径的程序

给定n个目录路径,我们需要编写一个程序来查找最长的公共目录路径。 例如:

null
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!

在函数中 最长公共路径() 使用的主要变量有两个: “共性” 用于存储常用字符的长度和 “CommonString” 用于存储最长的路径串,以便获得最长的公共路径。 CommonCharacter变量在每次迭代中都会根据输入路径中出现的公共路径的长度进行更新。 最后,我们得到了迭代后公共路径字符串的长度。然后,我们通过子串得到公共路径,直到分隔符 ‘/’ 犹如 如果我们不这样做,我们就会得到路径中最长的公共字符串,这不应该是我们的结果 . 以下是上述方法的实施情况。

CPP

// CPP program for longest common path
#include <bits/stdc++.h>
using namespace std;
string LongestCommonPath( const vector<string>& input_directory,
char separator)
{
vector<string>::const_iterator iter;
// stores the length of common characters
// and initialized with the length of
// first string .
int CommonCharacters = input_directory[0].length();
// stores the common string and initialized
// with the first string .
string CommonString = input_directory[0];
for (iter = input_directory.begin() + 1;
iter != input_directory.end(); iter++) {
// finding the two pointers through the mismatch()
// function which is 'mismatch at first string' and
//  'mismatch at the other string '
pair<string::const_iterator, string::const_iterator> p =
mismatch(CommonString.begin(),
CommonString.end(), iter->begin());
// As the first mismatch string pointer points to the mismatch
// present in the "CommonString" so "( p.first-CommonString.begin())"
// determines the common characters in each iteration .
if ((p.first - CommonString.begin()) < CommonCharacters) {
// If the expression is smaller than commonCharacters
// then we will update the commonCharacters because
// this states that common path is smaller than the
// string commonCharacters we have evaluated till .
CommonCharacters = p.first - CommonString.begin();
}
// Updating CommonString variable
// so that in this maximum length
// string is stored .
if (*iter > CommonString)
CommonString = *iter;
}
// In 'found' variable we store the index of '/' in
// the length of common characters in CommonString
int found;
for ( int i = CommonCharacters; i >= 0; --i) {
if (CommonString[i] == '/' ) {
found = i;
break ;
}
}
// The substring from index 0 to index of
// separator is the longest common substring
return CommonString.substr(0, found);
}
int main()
{
int n = 4;
string input_directory[4] = {
"/home/User/Desktop/gfg/test" ,
"/home/User/Desktop/gfg/file" ,
"/home/User/Desktop/gfg/folders" ,
"/home/User/Desktop/gfg/folders"
};
vector<string> input(input_directory,
input_directory + n);
cout << "Longest Common Path is "
<< LongestCommonPath(input, '/' ) << "!" ;
return 0;
}


输出:

Longest Common Path is /home/User/Desktop/gfg!

参考资料: 罗塞塔代码

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享