ID | Title | Difficulty | |
---|---|---|---|
Loading... |
555. Split Concatenated Strings
Medium
LeetCode
Array, String, Greedy
Problem
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.
Example 1:
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".
Example 2:
Input: strs = ["abc"]
Output: "cba"
Constraints:
- 1 <= strs.length <= 1000
- 1 <= strs[i].length <= 1000
- 1 <= sum(strs[i].length) <= 1000
- strs[i] consists of lowercase English letters.
Code
class Solution {
public String splitLoopedString(String[] strs) {
char maxChar = 'a';
for (int i = 0; i < strs.length; i++) {
String curr = strs[i];
for (char c : curr.toCharArray()) {
if (c > maxChar) maxChar = c;
}
String rev = reverse(curr);
if (strs[i].compareTo(rev) < 0) strs[i] = rev;
}
String res = "";
for (int i = 0; i < strs.length; i++) {
String maxStr = String.valueOf(maxChar);
String curr = strs[i];
String rev = reverse(curr);
if(curr.indexOf(maxStr) == -1 && rev.indexOf(maxStr) == -1) continue;
for (String temp: new String[] {curr, rev}) {
for (int k = 0; k < temp.length(); k++) {
if (temp.charAt(k) != maxChar) continue;
StringBuilder sb = new StringBuilder(temp.substring(k));
// 之后的字符串
for (int j = i + 1; j < strs.length; j++) sb.append(strs[j]);
// 之前的字符串
for (int j = 0; j < i; j++) sb.append(strs[j]);
sb.append(temp.substring(0, k));
if (sb.toString().compareTo(res) > 0) res = sb.toString();
}
}
}
return res;
}
private String reverse(String s) {
char[] arr = s.toCharArray();
int left = 0;
int right = arr.length - 1;
while(left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return String.valueOf(arr);
}
}
按 <- 键看上一题!
554. Brick Wall
按 -> 键看下一题!
556. Next Greater Element III