This is what I need to do:
Create a function that receives a text string, and a search string, and returns how many times the search string appears in the string, as a subsequence of its letters in order.
For example, if you receive the word "Hhoola" and the substring "hola", the answer would be 4, because you could take the first H with the first O (and with the L and with the A), the first H with the second O, the second H with the first O, or the second H with the second O. If you receive "hobla", the answer would be 1. If you receive "ohla", the answer would be 0, because after the H there is no O to complete the sequence in order.
This is what i got so far:
int count = 0;
void Function(string text, string subText)
{
for (int i = 0; i < text.Length; i )
{
if (text[i] == subText[0])
{
for (int j = 0; j < subText.Length; j )
{
if (text[i j] != subText[j])
{
break;
}
if (j == subText.Length - 1)
{
count ;
}
}
}
}
}
string text = Console.ReadLine().ToLower();
string subText = Console.ReadLine().ToLower();
ReceibeText(text, subText);
CodePudding user response:
The code should look like this. Code doesn't work but is close.
public class SubSequences
{
string input = "";
string word = "";
int count = 0;
public void FindMatches(string input, string word)
{
this.input = input;
this.word = word;
FindMatchesRecursive(0, 0);
}
public void FindMatchesRecursive(int inputIndex, int wordIndex)
{
for (int i = inputIndex; i < input.Length - word.Length; i )
{
for (int j = wordIndex; j < input.Length - word.Length; j )
{
if (word.Substring(i) == input.Substring(j))
{
if (j == word.Length)
{
FindMatchesRecursive(i 1, j 1);
}
else
{
Console.WriteLine("Word Matches");
}
}
}
}
}
CodePudding user response:
The following solution matches character one by one, and once an entire match is found, the value of count
is incremented.
int Function(String string, String substring)
{
int M = substring.Length;
int N = string.Length;
int count = 0;
for (int i = 0; i <= N - M; i ){
int j;
for (j = 0; j < M; j ) {
if (string[i j] != substring[j]) {
break;
}
}
if (j == M) {
count ;
j = 0;
}
}
return count;
}