Last active
December 14, 2015 12:59
-
-
Save Battleroid/5090641 to your computer and use it in GitHub Desktop.
Find common prefix among two strings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
template<typename T> | |
T getDiff(const T a, const T b) { | |
if (a >= b) | |
return a; | |
else if (b > a) | |
return b; | |
} | |
string getPrefix(const string a, const string b) { | |
string prefix; | |
for (int i = 0; i < getDiff(a.length(), b.length()); i++) { | |
if (a[i] == b[i]) { | |
prefix += a[i]; | |
} | |
} | |
return prefix; | |
} | |
int main () { | |
string one = "Test"; | |
string two = "Tesj"; | |
cout << "a: Test, b: Tesj" << endl; | |
cout << "longest portion: " << getDiff(one.length(), two.length()) << endl; | |
cout << "prefix: " << getPrefix(one, two) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment