Given a list of strings, 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, you need to find the lexicographically biggest string after cutting the loop, which will make the looped string into a regular one.
Specifically, to find the lexicographically biggest 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 biggest one among all the possible regular strings.
Solution:
思路: 模拟着做
Time Complexity: O() Space Complexity: O()
Solution Code:
public class Solution {
public String splitLoopedString(String[] strs) {
// 先各自翻转一下
for (int i = 0; i < strs.length; i++) {
String rev = new StringBuilder(strs[i]).reverse().toString();
if (strs[i].compareTo(rev) < 0)
strs[i] = rev;
}
String res = "";
// 尝试every str作为那个被cut的
for (int i = 0; i < strs.length; i++) {
String rev = new StringBuilder(strs[i]).reverse().toString();
// 比较其 翻转 和 没翻转
for (String st: new String[] {strs[i], rev}) {
// try every k 作为分界点
for (int k = 0; k < st.length(); k++) {
// 拼接其他strs到t
StringBuilder t = new StringBuilder(st.substring(k));
for (int j = i + 1; j < strs.length; j++)
t.append(strs[j]);
for (int j = 0; j < i; j++)
t.append(strs[j]);
t.append(st.substring(0, k));
// 看t是否最大
if (t.toString().compareTo(res) > 0)
res = t.toString();
}
}
}
return res;
}
}
网友评论