Iam having problem solving this code regarding longest common prefix!!Please help by giving the code in c! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Iam having problem solving this code regarding longest common prefix!!Please help by giving the code in c!

You are given a sequence of lower case alphabetical characters as input, say A[0], ..., A[N-1]. N will be at most 100. A prefix of the sequence is some initial segment of the string - that is, A[0], ..., A[K-1], for some integer K, 1 <= K <= N. You have to output the longest prefix which occurs multiple times in the string. If no prefix occurs again, you must output "NO". (without quotes) For example, if the input string is "ababaa", then the possible prefixes are {"a", "ab", "aba", "abab", "ababa", "ababaa"}. We can see that "a" occurs at indices 2, 4, and 5. The string "ab" occurs again in position 2. "aba" occurs in position 2. "abab" does not occur again in the string. So the longest prefix that occurs multiple times in the string is "aba".

28th Aug 2019, 12:20 PM
Lakshmi Narayana Naidu
Lakshmi Narayana Naidu - avatar
1 Answer
0
my phone is short on battery, I can't write the code. You can do it yourself, I believe in you. You have a string of characters: string [ 100 ] You need to use strncpy() (not strcpy) to copy the first #number# letters into another string, which we call anotherString[ 50 ]. (Use a for() and first time you copy only the first character, 2nd time the first 2, and so on...) Each time, you need to check if what you got in anotherString[ ] can be found in the rest of sting[ ] . You can do that by using strrstr() Tip: to consider string[ ] from the 13th position on, just use &string[ 13 ] Now if you find a match you go ahead with the for() otherwise you stop the for() and the counter of the for() tells you what's the longest prefix You can find the sting functions online, and don't forget to #include <string.h> in your code. Have a nice learning!
11th Oct 2020, 11:46 PM
Davide
Davide - avatar