给定两个字符串s和t 。任务是找到在字符串t中作为子序列出现的字符串S的某些前缀的最大长度。
例子 :
Input : s = "digger"
t = "biggerdiagram"
Output : 3
digger
biggerdiagram
Prefix "dig" of s is longest subsequence in t.
Input : s = "geeksforgeeks"
t = "agbcedfeitk"
Output : 4
一个简单的解决方案是考虑所有前缀加一个,然后检查s []的当前前缀是否为t []的子序列。最后返回最大前缀的长度。
一个有效的解决方案基于以下事实:要找到长度为n的前缀,我们必须首先找到长度为n – 1的前缀,然后在t中寻找s [n-1]。同样,要找到长度为n – 1的前缀,我们必须首先找到长度为n – 2的前缀,然后寻找s [n – 2],依此类推。
因此,我们保留一个计数器,该计数器存储找到的前缀的当前长度。我们将其初始化为0,然后从s的第一个字母开始,并在t上进行迭代,以查找第一个字母的出现。一旦遇到s的第一个字母,我们就会更新计数器并寻找第二个字母。我们会不断更新计数器并寻找下一个字母,直到找到字符串s或t中没有更多字母为止。
以下是此方法的实现:
C++
// C++ program to find maximum
// length prefix of one string
// occur as subsequence in another
// string.
#include
using namespace std;
// Return the maximum length
// prefix which is subsequence.
int maxPrefix(char s[], char t[])
{
int count = 0;
// Iterating string T.
for (int i = 0; i < strlen(t); i++)
{
// If end of string S.
if (count == strlen(s))
break;
// If character match,
// increment counter.
if (t[i] == s[count])
count++;
}
return count;
}
// Driven Code
int main()
{
char S[] = "digger";
char T[] = "biggerdiagram";
cout << maxPrefix(S, T)
<< endl;
return 0;
}
Java
// Java program to find maximum
// length prefix of one string
// occur as subsequence in another
// string.
public class GFG {
// Return the maximum length
// prefix which is subsequence.
static int maxPrefix(String s,
String t)
{
int count = 0;
// Iterating string T.
for (int i = 0; i < t.length(); i++)
{
// If end of string S.
if (count == s.length())
break;
// If character match,
// increment counter.
if (t.charAt(i) == s.charAt(count))
count++;
}
return count;
}
// Driver Code
public static void main(String args[])
{
String S = "digger";
String T = "biggerdiagram";
System.out.println(maxPrefix(S, T));
}
}
// This code is contributed by Sumit Ghosh
Python 3
# Python 3 program to find maximum
# length prefix of one string occur
# as subsequence in another string.
# Return the maximum length
# prefix which is subsequence.
def maxPrefix(s, t) :
count = 0
# Iterating string T.
for i in range(0,len(t)) :
# If end of string S.
if (count == len(s)) :
break
# If character match,
# increment counter.
if (t[i] == s[count]) :
count = count + 1
return count
# Driver Code
S = "digger"
T = "biggerdiagram"
print(maxPrefix(S, T))
# This code is contributed
# by Nikita Tiwari.
C#
// C# program to find maximum
// length prefix of one string
// occur as subsequence in
// another string.
using System;
class GFG
{
// Return the maximum length prefix
// which is subsequence.
static int maxPrefix(String s,
String t)
{
int count = 0;
// Iterating string T.
for (int i = 0; i < t.Length; i++)
{
// If end of string S.
if (count == s.Length)
break;
// If character match,
// increment counter.
if (t[i] == s[count])
count++;
}
return count;
}
// Driver Code
public static void Main()
{
String S = "digger";
String T = "biggerdiagram";
Console.Write(maxPrefix(S, T));
}
}
// This code is contributed by nitin mittal
PHP
输出 :
3