码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 1417. Reformat The String

时间:2020-04-26 17:18:34      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:文字   input   nbsp   nat   math   orm   记录   char   sam   

重新格式化字符串。给你一个混合了数字和字母的字符串 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

标签:文字   input   nbsp   nat   math   orm   记录   char   sam   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!