【字符串】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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章