You are given an array of strings strs. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops
Return the lexicographically largest string after cutting the loop, which will make the looped string into a regular one.
Specifically, to find the lexicographically largest string, you need to experience two phases:
Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.
Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint.
And your job is to find the lexicographically largest one among all the possible regular strings.
Input: strs =["abc","xyz"]Output: "zyxcba"Explanation: You can get the looped string "-abcxyz-","-abczyx-","-cbaxyz-","-cbazyx-", where '-' represents the looped status.The answer string came from the fourth looped one, where you could cut from the middle character 'a' and get "zyxcba".
To get the lexicographically largest string, we need to consider every possible way to reverse each string and every possible cut point in the loop. For each string, try both its original and reversed form, and for each character in that string, treat it as the cut point. By greedily choosing the best configuration for each string and cut, we can efficiently find the answer.
classSolution {
funsplitLoopedString(strs: Array<String>): String {
val n = strs.size
for (i in strs.indices) {
val rev = strs[i].reversed()
if (rev > strs[i]) strs[i] = rev
}
var ans = ""for (i in0 until n) {
val orig = strs[i]
val rev = orig.reversed()
for (cur in listOf(orig, rev)) {
for (k in cur.indices) {
var t = cur.substring(k)
for (j in1 until n) {
t += strs[(i + j) % n]
}
t += cur.substring(0, k)
if (t > ans) ans = t
}
}
}
return ans
}
}
classSolution:
defsplitLoopedString(self, strs: list[str]) -> str:
n = len(strs)
for i in range(n):
rev = strs[i][::-1]
if rev > strs[i]:
strs[i] = rev
ans =''for i in range(n):
orig = strs[i]
rev = orig[::-1]
for cur in [orig, rev]:
for k in range(len(cur)):
t = cur[k:]
for j in range(1, n):
t += strs[(i + j) % n]
t += cur[:k]
if t > ans:
ans = t
return ans
impl Solution {
pubfnsplit_looped_string(strs: Vec<String>) -> String {
let n = strs.len();
letmut strs = strs;
for i in0..n {
let rev: String = strs[i].chars().rev().collect();
if rev > strs[i] {
strs[i] = rev;
}
}
letmut ans = String::new();
for i in0..n {
let orig =&strs[i];
let rev: String = orig.chars().rev().collect();
for cur in [orig, &rev] {
for k in0..cur.len() {
letmut t = String::from(&cur[k..]);
for j in1..n {
t.push_str(&strs[(i + j) % n]);
}
t.push_str(&cur[..k]);
if t > ans {
ans = t;
}
}
}
}
ans
}
}