LeetCode 1417. Reformat The String


[Easy] LeetCode 1417. Reformat The String
リンク:https://leetcode.com/problems/reformat-the-string/
テーマ説明: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.
数字とアルファベットを混ぜた文字列sをあげます.その中のアルファベットはすべて小文字です.隣接する2つの文字のタイプが異なるように、文字列を再フォーマットしてください.つまり、アルファベットの後ろには数字がついていなければならないが、数字の後ろにはアルファベットがついていなければならない.再フォーマットされた文字列を返してください.必要に応じて再フォーマットできない場合は、空の文字列が返されます.
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”
Tag:Two Pointer解題構想この問題は私たちに文字列を与えて、文字列の中には数字と小文字のアルファベットが入っています.タイトルでは、同じタイプの文字が2回連続して現れないように、これらの文字を並べ直す必要があります.つまり、同じタイプの文字の間は、他のタイプの文字で区切らなければならない.入力した文字列が要求に達しない場合は、空の文字列を返します.
この問題は私が1周の解法を見て、すべてコードが長いので、私のコードはまだ短いです.まず2つのstringbufferで文字列のすべてのletterとdigitを記録し、2つの長さの差が1より大きいかどうかを判断し、ある場合は結果が得られないことを説明し、空の文字列に直接戻ります.letterの個数とdigitの個数が合併要件に合致する場合は,長さの長いものをトップに置く.例えば「111」と「aa」を合わせると、結果は必ず「1 a 1 a 1」になります.そうでなければ、「a」が先頭に立つと、すべての1を分割することはできません.だから私は新しい関数combineを利用して、頭文字が長い文字列に違いないことを保証しました.
TIME: O(N) SPACE: O(N)
解法1:
class Solution {
    public String reformat(String s) {
        StringBuffer letter = new StringBuffer(), digit = new StringBuffer();
        for(char c: s.toCharArray()){
            if(Character.isLetter(c)) letter.append(c);
            else digit.append(c);
        }
        
        if(Math.abs(digit.length()-letter.length()) >1) return "";
        
        if(digit.length() > letter.length()){
            return combine(digit, letter);
        }else{
            return combine(letter, digit);
        }
    }
    
    public String combine(StringBuffer a, StringBuffer b){
        // a string is always equal or longer than b
        StringBuffer res= new StringBuffer();
        int t1 = 0, t2 =0;
        
        while(t1 < a.length() || t2 < b.length()){
            if(t1 < a.length()) res.append(a.charAt(t1++));
            if(t2 < b.length()) res.append(b.charAt(t2++));
        }
        
        return res.toString();
    }
}