Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 27, 2016 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/66e8b6637e68cd0a94e6c0ab99509b35 to your computer and use it in GitHub Desktop.
Save jianminchen/66e8b6637e68cd0a94e6c0ab99509b35 to your computer and use it in GitHub Desktop.
longest common substring - brute force solution O(n^3) - first writing, 2 bugs, need the debugger; static analysis catching one bug only
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)
{
//cur = maximum; // bug001 - opposite
maximum = cur;
int lastPos = start1 - 1; // s1 - start: i, end: lastPos
res = s1.Substring(i, lastPos - i + 1); //no index out-of-range error
}
break; // bug002 - forget to add break! first writing, otherwise, deadloop!
}
}
}
return res;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment