[LeetCode] Split Concatenated Strings

555. Split Concatenated Strings

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:

  1. Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.
  2. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string splitLoopedString(vector<string>& strs) {
string res = "a", all = "";
for(auto s : strs) {
string rev = s;
reverse(begin(rev),end(rev));
all += max(rev,s);
}
for(int i = 0, cut = 0; i < strs.size(); cut += strs[i].length(), i++) {
string now = strs[i], rev = strs[i], rest = all.substr(cut + strs[i].length()) + all.substr(0, cut);
reverse(begin(rev),end(rev));
for(int j = 0; j < now.length(); j++) {
res = max(res, now.substr(j) + rest + now.substr(0,j));
res = max(res, rev.substr(j) + rest + rev.substr(0,j));
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/27/PS/LeetCode/split-concatenated-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.