[LeetCode] 1417. 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.

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.

重新格式化字符串。

给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。

请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。

请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reformat-the-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是将input分成digits和characters两个list,若两者的长度差大于等于2则一定是一个无效解,直接return false。常规情况就是按照digits和characters的长度,谁长,谁就拿出一个来attach到StringBuilder的末端,用一个boolean变量去记录两者谁一开始更长,更长的先开始往StringBuilder里添加,然后互相交替。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public String reformat(String s) {
 3         List<Character> digits = new ArrayList<>();
 4         List<Character> characters = new ArrayList<>();
 5         for (char c : s.toCharArray()) {
 6             if (Character.isDigit(c)) {
 7                 digits.add(c);
 8             } else {
 9                 characters.add(c);
10             }
11         }
12         if (Math.abs(digits.size() - characters.size()) >= 2) {
13             return "";
14         }
15 
16         StringBuilder sb = new StringBuilder();
17         boolean digit = (digits.size() >= characters.size() ? true : false);
18         for (int i = 0; i < s.length(); i++) {
19             if (digit) {
20                 sb.append(digits.remove(0));
21             } else {
22                 sb.append(characters.remove(0));
23             }
24             digit = !digit;
25         }
26         return sb.toString();
27     }
28 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12780505.html