【蓝桥杯】压缩字符串

题目:

解题思路:

遍历字符串,每个字符与前一个字符比较,若相同 count + 1 ,若不同,将 temp 添加至新字符串末尾,并更新 temp ,同时若 count > 1 (即本字符出现多次,可以压缩), 将 count 添加至新字符串末尾。同时利用 falg判断是否进行压缩操作。

java 复制代码
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        //在此输入您的代码...
        String str = scan.nextLine();
        StringBuilder ans = new StringBuilder();
        char temp = str.charAt(0);
        int count = 1;
        boolean flag = false;  // 判断是否压缩

        for (int i = 1; i < str.length(); i++) {
          if (temp == str.charAt(i)){
            count++;
          }
          else {
            ans.append(temp);
            temp = str.charAt(i);
            if (count > 1) {
              ans.append(count);
              count = 1;
              flag = true;  // 进行了压缩
            }
          }
        }
        //处理最后一个字符
        ans.append(temp);
        if (count > 1) {
              ans.append(count);
              flag = true;
            }

        if (!flag) {
          System.out.println("NO");
        }
        else {
          System.out.println(ans);
        }
        scan.close();
    }
}
相关推荐
张人玉20 分钟前
C# 常量与变量
java·算法·c#
Java技术小馆34 分钟前
GitDiagram如何让你的GitHub项目可视化
java·后端·面试
Codebee1 小时前
“自举开发“范式:OneCode如何用低代码重构自身工具链
java·人工智能·架构
weixin_446122461 小时前
LinkedList剖析
算法
程序无bug1 小时前
手写Spring框架
java·后端
程序无bug1 小时前
Spring 面向切面编程AOP 详细讲解
java·前端
全干engineer1 小时前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Fireworkitte1 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
GodKeyNet2 小时前
设计模式-责任链模式
java·设计模式·责任链模式
a_Dragon12 小时前
Spring Boot多环境开发-Profiles
java·spring boot·后端·intellij-idea