Greetings.
Given K arrays (0 <K <10) containing strings. It is necessary to find the largest (by the number of characters) string found in all K arrays. Do not advise the algorithm or code?
Thank you in advance.
Solution for line
K
11111111
.Pseudo java code:
String[][] arrays = ...; //ввод данных Map<String, Integer> map = new HashMap<>(); for (int k = 0; k < arrays.length; k++) { for (String str: arrays[k]) { int mask = 1 << k; if (map.contains(str)) { map.put(str, map.get(str) & mask); } else { map.put(str, mask); } } } String longest = ""; for (String str : map.getKeys()) { if (map.get(str) == (1 << input.length) - 1 && longest.lenght < str.length) { longest = str; } } System.out.println(longest);
@andrewshka taking into account the unimportance of the language, here is an example
import Data.List (sortBy, foldl1') import qualified Data.Set as S input = [["abracadabra", "good", "fuck"], ["abracadabra", "bad", "fuck"], ["abracadabra", "aaaaaaaaaaaaaaaaaaaaaa", "fuck", "fuck"]] out = fst $ head $ sortBy (\(_,x) (_,y) -> compare yx) $ map (\x -> (x, length x)) $ S.toList $ foldl1' S.intersection $ map S.fromList input main = print out
FirstOrDefault
with option
? - VladDIf the language is not important, here’s C #:
arrays.First() .Where(s => arrays.Skip(1).All(a => a.Contains(s)) .OrderByDescending(s => s.Length) .FirstOrDefault()
Or so:
arrays.Aggregate((intersection, next) => intersection.Intersect(next)) .OrderByDescending(s => s.Length) .FirstOrDefault();
(the search speed of the intersection O (total size), the speed of the combination OrderBy
+ First
O (the size of the intersection)).
Source: https://ru.stackoverflow.com/questions/222731/
All Articles