【字符串】C037_LC_重新格式化字符串(思维题)

一、Problem

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.

Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.

二、Solution

方法一:轮流

  • 分别存储字符与数字
  • 然后,按照谁多谁先 poll 的原则添加到 sb 中。

小优化:我们的原则是让数量多的先 append,所以我们可以固定一个,只不过在 append 之前先将 alp 与 dig 交换。

class Solution {
    public String reformat(String s) {
        char[] ss = s.toCharArray();
        LinkedList<Character> alp = new LinkedList<>(), dig = new LinkedList<>();
        for (char c : ss) {
            if (c >= '0' && c <= '9') dig.add(c);
            if (c >= 'a' && c <= 'z') alp.add(c);
        }
        if (Math.abs(dig.size()-alp.size()) >= 2) 
           return ""; 
        StringBuilder sb = new StringBuilder();
        while (!dig.isEmpty() || !alp.isEmpty()) {
            if (alp.size() > dig.size()) {
                if (!alp.isEmpty()) sb.append(alp.poll());
                if (!dig.isEmpty()) sb.append(dig.poll());
            } else {
                if (!dig.isEmpty()) sb.append(dig.poll());
                if (!alp.isEmpty()) sb.append(alp.poll());
            }
        }
        return sb.toString();
    }
}

复杂度分析

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章