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,其中的字母均为小写英文字母。
请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。
请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。

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
解题思路
这道题目给我们一个字符串,字符串内都是数字和小写的字母。题目要求我们重新排列这些字符,使得同一个类型的字符不会连续出现两次。也就是说同一类型的字符中间必须被其他类型的字符间隔开来。如果输入的字符串没有办法达到要求,那么就返回一个空字符串。

这道题目我看了一圈的解法,都是代码很长,我的代码还算是短的了。
我们首先用两个stringbuffer记录字符串里面的所有letter和digit,然后判断一下两个长度差有没有大于1,如果有的话说明不可能产生结果,直接返回空字符串。
如果letter的个数和digit的个数符合合并要求的话,我们要把长度较长的放在首位。比如说"111"和"aa"合并的话,结果一定是"1a1a1",否则如果’a’打头的话,没有办法将所有的1分割开。
所以我利用了一个新的函数combine,保证了首字母一定是较长的字符串。

TIME: O(N)
SPACE: O(N)

解法一:

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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值