Created
July 27, 2016 20:42
-
-
Save jianminchen/b75fb58837ffc49abdb6b04aa6218f02 to your computer and use it in GitHub Desktop.
longest common substring - brute force solution - O(n^3) - code after reviewing.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace longestCommonSubstring | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string test = longestCommonSubstring("abc123def","hij123klmn"); | |
} | |
/* | |
* July 27, 2016 | |
* | |
* Design: | |
* Using the start position as a variable to do brute force search, | |
* Two strings - common substring | |
* iterate one string on start position, | |
* iterate second string on start position as well | |
* | |
* Time complexity - O(n^4) -> O(n^3) | |
* instead of two variables - start position and end position - O(n^4) | |
* | |
* Read C++ code fist to get the idea, | |
* | |
* and then, write C# code | |
* | |
* Target: try to finish it in 20 minutes in first writing. | |
*/ | |
public static string longestCommonSubstring(string s1, string s2) | |
{ | |
if (s1 == null || s1.Length == 0 || s2 == null || s2.Length == 0) | |
return string.Empty; | |
int len1 = s1.Length; | |
int len2 = s2.Length; | |
int maximum = 0; | |
string res = string.Empty; | |
for(int i=0; i<len1; i++ ) | |
for (int j = 0; j < len2; j++) | |
{ | |
int start1 = i; | |
int start2 = j; | |
int cur = 0; | |
while (start1 < len1 && start2 < len2) | |
{ | |
char c1 = s1[start1]; | |
char c2 = s2[start2]; | |
if (c1 == c2) | |
{ | |
start1++; | |
start2++; | |
cur++; | |
} | |
else | |
{ | |
if (cur > maximum) | |
{ | |
maximum = cur; | |
// get substring from s1 - start/ end position | |
int end = start1 - 1; // s1 - start: i, end: start1 -1 | |
res = s1.Substring(i, end - i + 1); | |
} | |
break; | |
} | |
} | |
} | |
return res; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This does not work. try longestCommonSubstring("wonderfulhelloare", "helhelloare")