0

Longest Common Substring (task)

Task: Given multiple words, you need to find the longest string that is a substring of all words. Input Format: A string of words, separated by spaces. The string can also contain numbers. Output Format: A string, representing the longest common substring. If there are multiple longest common substrings, output the smallest one in alphabetical order. Sample Input: SoloLearn Learning LearningIsFun Learnable Sample Output: Learn My code failed in a task 4. I can't find an error in a code. Help) https://code.sololearn.com/cXd691C4aYTW/?ref=app

10th Aug 2020, 3:26 PM
Jhon Doe
Jhon Doe - avatar
4 Answers
+ 2
Jhon Doe Try below. text = input().split() from itertools import permutations words = set() for i in range(0, len(text[0:])+2): for j in permutations(text[0], i): words.add(''.join(j)) substrings = [] for word in words: count = 0 for i in text: if word in i: count += 1 if count == len(text): substrings.append(word) substrings.sort(key=len, reverse=True) print(substrings[0])
3rd Jun 2021, 7:32 PM
Swapnil Kamdi
Swapnil Kamdi - avatar
+ 1
10th Aug 2020, 6:55 PM
Jhon Doe
Jhon Doe - avatar
+ 1
// Hello where. Here is My version on C#. it pass all 6 tests: https://www.sololearn.com/ru/compiler-playground/c81zxq1Buzf4 using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string[] words = Console.ReadLine().Split(' '); Array.Sort(words, (x, y) => x.Length.CompareTo(y.Length)); string word = words[0]; int length = word.Length; for (int i = length; i > 0; i--) { HashSet<string> substrings = new HashSet<string>(); for (int j = 0; j <= length - i; j++) { substrings.Add(word.Substring(j, i)); } List<string> ok = substrings.Where(ss => words.Skip(1).All(w => w.Contains(ss))).OrderBy(s => s).ToList(); if (ok.Any()) { Console.WriteLine(ok[0]); break; } } } }
8th Jan 2024, 2:34 PM
Š˜Š³Š¾Ń€ŃŒ ŠŠŗŠ°Ń‚Š¾Š²
Š˜Š³Š¾Ń€ŃŒ ŠŠŗŠ°Ń‚Š¾Š² - avatar
0
It worked! def main(word): a=[] for n in range(int(len(word)/2)+1): for i in range(len(word)-1): a.append(word[0:i+1]) a.append(word[i+1:]) a.append(word) word=word[1:-1] return a c=[] words=input().split() for word in words: c.append(set(main(word))) result=sorted(set.intersection(*c), key=len, reverse=True) print(result[0])
25th Oct 2023, 7:17 PM
Denis
Denis - avatar