原文:

给定一个字符串 str ,任务是找到最长的前缀,也是给定字符串的后缀。前缀和后缀不应重叠。如果没有这样的前缀,则打印 -1

示例:

输入: str = "aabcdaabc" 输出: aabc 字符串“aabc”是最长的 前缀,也是后缀。

输入:str = " aaaa " t3】输出: aa

做法:思路是采用 搜索的预处理算法。在该算法中,我们构建 lps 数组,该数组存储以下值:

lps[i] =最长的前缀 pat[0..i] 也是pat【0】的后缀..i]

我们用上面的方法得到长度,然后从前面打印相同数量的字符,这就是我们的答案。

下面是上述方法的实现:

c

// c   implementation of the approach
#include 
using namespace std;
// returns length of the longest prefix
// which is also suffix and the two do
// not overlap. this function mainly is
// copy of computelpsarray() in kmp algorithm
int lengthlongestprefixsuffix(string s)
{
    int n = s.length();
    int lps[n];
    // lps[0] is always 0
    lps[0] = 0;
    // length of the previous
    // longest prefix suffix
    int len = 0;
    // loop to calculate lps[i]
    // for i = 1 to n - 1
    int i = 1;
    while (i < n) {
        if (s[i] == s[len]) {
            len  ;
            lps[i] = len;
            i  ;
        }
        else {
            // this is tricky. consider
            // the example. aaacaaaa
            // and i = 7\. the idea is
            // similar to search step.
            if (len != 0) {
                len = lps[len - 1];
                // also, note that we do
                // not increment i here
            }
            // if len = 0
            else {
                lps[i] = 0;
                i  ;
            }
        }
    }
    int res = lps[n - 1];
    // since we are looking for
    // non overlapping parts
    return (res > n / 2) ? n / 2 : res;
}
// function that returns the prefix
string longestprefixsuffix(string s)
{
    // get the length of the longest prefix
    int len = lengthlongestprefixsuffix(s);
    // stores the prefix
    string prefix = "";
    // traverse and add characters
    for (int i = 0; i < len; i  )
        prefix  = s[i];
    // returns the prefix
    return prefix;
}
// driver code
int main()
{
    string s = "abcab";
    string ans = longestprefixsuffix(s);
    if (ans == "")
        cout << "-1";
    else
        cout << ans;
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java implementation of the approach
class gfg
{
// returns length of the longest prefix
// which is also suffix and the two do
// not overlap. this function mainly is
// copy of computelpsarray() in kmp algorithm
static int lengthlongestprefixsuffix(string s)
{
    int n = s.length();
    int lps[] = new int[n];
    // lps[0] is always 0
    lps[0] = 0;
    // length of the previous
    // longest prefix suffix
    int len = 0;
    // loop to calculate lps[i]
    // for i = 1 to n - 1
    int i = 1;
    while (i < n)
    {
        if (s.charat(i) == s.charat(len))
        {
            len  ;
            lps[i] = len;
            i  ;
        }
        else
        {
            // this is tricky. consider
            // the example. aaacaaaa
            // and i = 7\. the idea is
            // similar to search step.
            if (len != 0)
            {
                len = lps[len - 1];
                // also, note that we do
                // not increment i here
            }
            // if len = 0
            else
            {
                lps[i] = 0;
                i  ;
            }
        }
    }
    int res = lps[n - 1];
    // since we are looking for
    // non overlapping parts
    return (res > n / 2) ? n / 2 : res;
}
// function that returns the prefix
static string longestprefixsuffix(string s)
{
    // get the length of the longest prefix
    int len = lengthlongestprefixsuffix(s);
    // stores the prefix
    string prefix = "";
    // traverse and add characters
    for (int i = 0; i < len; i  )
        prefix  = s.charat(i);
    // returns the prefix
    return prefix;
}
// driver code
public static void main(string[] args)
{
    string s = "abcab";
    string ans = longestprefixsuffix(s);
    if (ans == "")
        system.out.println("-1");
    else
        system.out.println(ans);
}
}

python 3

# python 3 implementation of the approach
# returns length of the longest prefix
# which is also suffix and the two do
# not overlap. this function mainly is
# copy of computelpsarray() in kmp algorithm
def lengthlongestprefixsuffix(s):
    n = len(s)
    lps = [0 for i in range(n)]
    # length of the previous
    # longest prefix suffix
    len1 = 0
    # loop to calculate lps[i]
    # for i = 1 to n - 1
    i = 1
    while (i < n):
        if (s[i] == s[len1]):
            len1  = 1
            lps[i] = len1
            i  = 1
        else:
            # this is tricky. consider
            # the example. aaacaaaa
            # and i = 7\. the idea is
            # similar to search step.
            if (len1 != 0):
                len1 = lps[len1 - 1]
                # also, note that we do
                # not increment i here
            # if len = 0
            else:
                lps[i] = 0
                i  = 1
    res = lps[n - 1]
    # since we are looking for
    # non overlapping parts
    if (res > int(n / 2)):
        return int(n / 2)
    else:
        return res
# function that returns the prefix
def longestprefixsuffix(s):
    # get the length of the longest prefix
    len1 = lengthlongestprefixsuffix(s)
    # stores the prefix
    prefix = ""
    # traverse and add characters
    for i in range(len1):
        prefix  = s[i]
    # returns the prefix
    return prefix
# driver code
if __name__ == '__main__':
    s = "abcab"
    ans = longestprefixsuffix(s)
    if (ans == ""):
        print("-1")
    else:
        print(ans)
# this code is contributed by
# surendra_gangwar

c

// c# implementation of the approach
using system;
class gfg
{
    // returns length of the longest prefix
    // which is also suffix and the two do
    // not overlap. this function mainly is
    // copy of computelpsarray() in kmp algorithm
    static int lengthlongestprefixsuffix(string s)
    {
        int n = s.length;
        int []lps = new int[n];
        // lps[0] is always 0
        lps[0] = 0;
        // length of the previous
        // longest prefix suffix
        int len = 0;
        // loop to calculate lps[i]
        // for i = 1 to n - 1
        int i = 1;
        while (i < n)
        {
            if (s[i] == s[len])
            {
                len  ;
                lps[i] = len;
                i  ;
            }
            else
            {
                // this is tricky. consider
                // the example. aaacaaaa
                // and i = 7\. the idea is
                // similar to search step.
                if (len != 0)
                {
                    len = lps[len - 1];
                    // also, note that we do
                    // not increment i here
                }
                // if len = 0
                else
                {
                    lps[i] = 0;
                    i  ;
                }
            }
        }
        int res = lps[n - 1];
        // since we are looking for
        // non overlapping parts
        return (res > n / 2) ? n / 2 : res;
    }
    // function that returns the prefix
    static string longestprefixsuffix(string s)
    {
        // get the length of the longest prefix
        int len = lengthlongestprefixsuffix(s);
        // stores the prefix
        string prefix = "";
        // traverse and add characters
        for (int i = 0; i < len; i  )
            prefix  = s[i];
        // returns the prefix
        return prefix;
    }
    // driver code
    public static void main()
    {
        string s = "abcab";
        string ans = longestprefixsuffix(s);
        if (ans == "")
            console.writeline("-1");
        else
            console.writeline(ans);
    }
}
// this code is contributed by ryuga

java 描述语言


output: 

ab