Formatted question description: https://leetcode.ca/all/1417.html

1417. Reformat The String

Level

Easy

Description

Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).

You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.

Return the reformatted string or return an empty string if it is impossible to reformat the string.

Example 1:

Input: s = “a0b1c2”

Output: “0a1b2c”

Explanation: No two adjacent characters have the same type in “0a1b2c”. “a0b1c2”, “0a1b2c”, “0c2a1b” are also valid permutations.

Example 2:

Input: s = “leetcode”

Output: “”

Explanation: “leetcode” has only characters so we cannot separate them by digits.

Example 3:

Input: s = “1229857369”

Output: “”

Explanation: “1229857369” has only digits so we cannot separate them by characters.

Example 4:

Input: s = “covid2019”

Output: “c2o0v1i9d”

Example 5:

Input: s = “ab123”

Output: “1a2b3”

Constraints:

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters and/or digits.

Solution

Use two queues to store the letters and the digits in s respectively. Then check both queues’ sizes. If the sizes differ more than 1, then it is impossible to reformat the string, so return an empty string. Otherwise, if the sizes differ by exactly 1, then starting with the queue with a greater size, poll elements from both queues by turn to reformat the string. If the sizes are the same, then reformat the string starting with either queue is possible.

class Solution {
    public String reformat(String s) {
        Queue<Character> letterQueue = new LinkedList<Character>();
        Queue<Character> digitQueue = new LinkedList<Character>();
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (Character.isLetter(c))
                letterQueue.offer(c);
            else
                digitQueue.offer(c);
        }
        int letterCounts = letterQueue.size(), digitCounts = digitQueue.size();
        if (Math.abs(letterCounts - digitCounts) > 1)
            return "";
        else if (digitCounts > letterCounts) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < letterCounts; i++) {
                sb.append(digitQueue.poll());
                sb.append(letterQueue.poll());
            }
            sb.append(digitQueue.poll());
            return sb.toString();
        } else {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < digitCounts; i++) {
                sb.append(letterQueue.poll());
                sb.append(digitQueue.poll());
            }
            if (letterCounts > digitCounts)
                sb.append(letterQueue.poll());
            return sb.toString();
        }
    }
}

All Problems

All Solutions