Reputation: 49
If I am having a string
say for an example "ABEFAB"
, it would take a length parameter (eg. 2)
and then return a result which would show that there ARE identical substrings
of that length in my string
.
Upvotes: 0
Views: 111
Reputation: 186678
The simplest (however not that efficient) solution is
public static Boolean HasIdenticalSubStrings(String value, int length)
{
if (length <= 0)
return false;
else if (String.IsNullOrEmpty(value))
return false;
else if (value.Length <= length)
return false;
// HashSet is more efficient than List for Contains() operation
HashSet<String> subStrings = new HashSet<String>();
for (int i = 0; i <= value.Length - length; ++i) {
String s = value.Substring(i, length);
if (subStrings.Contains(s))
return true;
else
subStrings.Add(s);
}
return false;
}
Test cases:
HasIdenticalSubStrings("AAA", 2); // true, overlaping "AA" substrings
HasIdenticalSubStrings("ABxyAB", 2); // true
HasIdenticalSubStrings("ABxAB", 2); // true
HasIdenticalSubStrings("ABCDEF", 2); // false
Upvotes: 1
Reputation: 48568
I think you are looking for this
public static bool HasIdenticalSubStrings(string str, int len)
{
bool returnValue = false;
List<String> lst = new List<string>();
for (int i = 0; i <= str.Length - len; i++)
lst.Add(str.Substring(i, len));
returnValue = (lst.Distinct().Count() != lst.Count);
return returnValue;
}
and call like
HasIdenticalSubStrings("ABEFAB", 2); //return true
HasIdenticalSubStrings("ABCDEF", 2); //return false
Note: You need to put some checks like String.IsNullOrEmpty
check
Efficient Method:
public static bool HasIdenticalSubStrings(string str, int len)
{
bool returnValue = false;
List<String> lst = new List<string>();
for (int i = 0; i <= str.Length - len; i++)
{
String tempstr = str.Substring(i, len);
if (lst.Contains(tempstr))
{
returnValue = true;
break;
}
else
lst.Add(tempstr);
}
return returnValue;
}
Upvotes: 1
Reputation: 49
I think Contains
surves this puprose quite well. It doesn't take any length parameters, though, but I discovered that for my program it's not even necessary because there is a determined block size which I use.
Upvotes: 0