반응형
You are given an array(list) strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.
Examples:
strarr = ["tree", "foling", "trashy", "blue", "abcdef", "uvwxyz"], k = 2
Concatenate the consecutive strings of strarr by 2, we get:
treefoling (length 10) concatenation of strarr[0] and strarr[1]
folingtrashy (" 12) concatenation of strarr[1] and strarr[2]
trashyblue (" 10) concatenation of strarr[2] and strarr[3]
blueabcdef (" 10) concatenation of strarr[3] and strarr[4]
abcdefuvwxyz (" 12) concatenation of strarr[4] and strarr[5]
Two strings are the longest: "folingtrashy" and "abcdefuvwxyz".
The first that came is "folingtrashy" so
longest_consec(strarr, 2) should return "folingtrashy".
In the same way:
longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"
n being the length of the string array, if n = 0 or k > n or k <= 0 return "" (return Nothing in Elm, "nothing" in Erlang).
Note
consecutive strings : follow one after another without an interruption
Solution:
from typing import List, Optional
def longest_consec(strarr: List[Optional[str]], k: int):
if k <= 0 or len(strarr) < k:
return ''
concated_arr = [''.join(strarr[i:i+k]) for i in range(len(strarr))]
sorted_arr = sorted(concated_arr, key=len, reverse=True)
return sorted_arr[0]
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Playing with digits (0) | 2022.08.15 |
---|---|
Give me a Diamond (0) | 2022.08.14 |
Maximum subarray sum (0) | 2022.08.12 |
List Filtering (0) | 2022.08.11 |
Sum of a sequence (0) | 2022.08.10 |