555. Split Concatenated Strings

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:

  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 biggest one among all the possible regular strings.

Example:

Input: "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".

Note:

  1. The input strings will only contain lowercase letters.
  2. The total length of all the strings will not over 1,000.

Rust Solution

struct Solution;

use std::cmp::Ordering::Less;

impl Solution {
    fn split_looped_string(mut strs: Vec<String>) -> String {
        let n = strs.len();
        strs = strs
            .into_iter()
            .map(|s| {
                let a = s.to_string();
                let b = s.chars().rev().collect();
                if let Less = a.cmp(&b) {
                    b
                } else {
                    a
                }
            })
            .collect();
        let mut max = strs.join("");
        for i in 0..n {
            let left = strs[..i].join("");
            let right = strs[i + 1..].join("");
            let m = strs[i].len();
            let a = strs[i].to_string();
            let b = a.chars().rev().collect();
            for s in &[a, b] {
                for j in 0..m {
                    let mut t = "".to_string();
                    t.push_str(&s[j..]);
                    t.push_str(&right);
                    t.push_str(&left);
                    t.push_str(&s[..j]);
                    max = if let Less = max.cmp(&t) { t } else { max };
                }
            }
        }
        max
    }
}

#[test]
fn test() {
    let strs = vec_string!["abc", "xyz"];
    let res = "zyxcba".to_string();
    assert_eq!(Solution::split_looped_string(strs), res);
    let strs = vec_string!["a", "b", "c"];
    let res = "cab".to_string();
    assert_eq!(Solution::split_looped_string(strs), res);
}

Having problems with this solution? Click here to submit an issue on github.