[LeetCode] 1417. Reformat The String

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 1417. 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"

思路是将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] 1417. Reformat The String的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 1417. Reformat The String

Leetcode 1417. Reformat The String

[LeetCode] 1417. Reformat The String

LeetCode 1417. 重新格式化字符串

LeetCode --- 1507. Reformat Date 解题报告

LeetCode --- 1507. Reformat Date 解题报告