LeetCode 题解工作台

重新格式化字符串

给你一个混合了数字和字母的字符串 s ,其中的字母均为小写英文字母。 请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。 请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。 示例 1: 输入: s =…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

将字符串 中的所有字符分成“数字”、“字母”两类,分别放入 , 两个数组中。 比较 , 两个数组的长度,若 长度小于 ,则交换 , 。接着判断两个数组长度差,若超过 ,则返回空字符串。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

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

 

示例 1:

输入:s = "a0b1c2"
输出:"0a1b2c"
解释:"0a1b2c" 中任意两个相邻字符的类型都不同。 "a0b1c2", "0a1b2c", "0c2a1b" 也是满足题目要求的答案。

示例 2:

输入:s = "leetcode"
输出:""
解释:"leetcode" 中只有字母,所以无法满足重新格式化的条件。

示例 3:

输入:s = "1229857369"
输出:""
解释:"1229857369" 中只有数字,所以无法满足重新格式化的条件。

示例 4:

输入:s = "covid2019"
输出:"c2o0v1i9d"

示例 5:

输入:s = "ab123"
输出:"1a2b3"

 

提示:

  • 1 <= s.length <= 500
  • s 仅由小写英文字母和/或数字组成。
lightbulb

解题思路

方法一:模拟

将字符串 ss 中的所有字符分成“数字”、“字母”两类,分别放入 aa, bb 两个数组中。

比较 aa, bb 两个数组的长度,若 aa 长度小于 bb,则交换 aa, bb。接着判断两个数组长度差,若超过 11,则返回空字符串。

接着同时遍历两个数组,依次添加 aa, bb 中对应字符到答案中。遍历结束,若 aa 长度大于 bb,则添加 aa 的最后一个字符到答案中。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def reformat(self, s: str) -> str:
        a = [c for c in s if c.islower()]
        b = [c for c in s if c.isdigit()]
        if abs(len(a) - len(b)) > 1:
            return ''
        if len(a) < len(b):
            a, b = b, a
        ans = []
        for x, y in zip(a, b):
            ans.append(x + y)
        if len(a) > len(b):
            ans.append(a[-1])
        return ''.join(ans)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on whether the candidate can identify edge cases like strings containing only letters or digits.

  • question_mark

    Evaluate their understanding of string-driven solution strategies and balancing character types.

  • question_mark

    Check if they are able to explain the time and space complexities clearly and concisely.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle edge cases where there are no letters or no digits, leading to incorrect answers.

  • error

    Incorrectly assuming that the order of characters doesn't matter in terms of type adjacency.

  • error

    Not considering cases where the counts of letters and digits differ by more than 1, leading to wrong results.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling strings with a mix of uppercase and lowercase letters.

  • arrow_right_alt

    Optimizing the solution for very large strings close to the maximum input size.

  • arrow_right_alt

    Allowing spaces or other characters in the input string.

help

常见问题

外企场景

重新格式化字符串题解:String-driven solution … | LeetCode #1417 简单