• ​力扣解法汇总1417-重新格式化字符串


     目录链接:

    力扣编程题-解法汇总_分享+记录-CSDN博客

    GitHub同步刷题项目:

    https://github.com/September26/java-algorithms

    原题链接:

    力扣


    描述:

    给你一个混合了数字和字母的字符串 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 仅由小写英文字母和/或数字组成。

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

    解题思路:

    * 解题思路:
    * 把s分割成字符,然后按照数字,字母分为两个集合。
    * 如果两个集合的长度之差大于等于2,则就没有符合的。
    * 否则依次一个集合取一个

    代码:

    1. public class Solution1417 {
    2. public String reformat(String s) {
    3. char[] chars = s.toCharArray();
    4. List numList = new ArrayList<>();
    5. List letterList = new ArrayList<>();
    6. for (char c : chars) {
    7. if (c >= '0' && c <= '9') {
    8. numList.add(c);
    9. } else {
    10. letterList.add(c);
    11. }
    12. }
    13. List longerList;
    14. List shortList;
    15. if (numList.size() >= letterList.size()) {
    16. longerList = numList;
    17. shortList = letterList;
    18. } else {
    19. longerList = letterList;
    20. shortList = numList;
    21. }
    22. if (longerList.size() - shortList.size() >= 2) {
    23. return "";
    24. }
    25. StringBuilder builder = new StringBuilder();
    26. for (int i = 0; i < longerList.size(); i++) {
    27. builder.append(longerList.get(i));
    28. if (i >= shortList.size()) {
    29. break;
    30. }
    31. builder.append(shortList.get(i));
    32. }
    33. return builder.toString();
    34. }
    35. }

  • 相关阅读:
    前端开发引入element plus与windi css
    Abaqus2023新功能:分析技术
    [I2C]I2C通信协议详解(二) --- I2C时序及规格指引
    可执行jar包和可依赖jar包同时生效
    【Qt】常用控件或属性(1)
    C++ 数据结构 哈弗曼树的制作
    ARM架构与编程 · 基于IMX6ULL
    小黑leetcode之旅:86. 分隔链表
    创建虚拟python开发环境
    阅读JDK源码的经验分享
  • 原文地址:https://blog.csdn.net/AA5279AA/article/details/126279939