分割均衡字符串 - 华为OD统一考试(C卷)

OD统一考试(C卷)

分值: 100分

题解: Java / Python / C++

alt

题目描述

均衡串定义:字符串只包含两种字符,且两种字符的个数相同。

给定一个均衡字符串,请给出可分割成新的均衡子串的最大个数。

约定字符串中只包含大写的’X"和’Y’两种字符。

输入描述

均衡串:XXYYXY

字符串的长度[2,10000]。给定的字符用均为均衡串。

输出描述

可分割为两个子串:

XXYY

XY

示例1

输入
XXYYXY

输出
2

备注
分割后的子串,是原字符串的连续子串。

题解

题目类型:贪心

解题思路:遍历字符串,统计字符’X’和’Y’的数量。当某个字符的数量达到字符串长度的一半时,将结果加1,并将该字符的数量重置为0。

C++

#include <iostream>
#include <string>
using namespace std;

int main() {
   
    string s;
    cin >> s;
    int rs = 0,w = 0, cnt = 0;
    char C = s[0];
    for (int i = 0; i < s.length(); i++) {
   
        w++;
        if (C == s[i]) cnt++;

        if (cnt > 0 && cnt * 2 == w) {
   
            rs++;
            cnt = 0;
            w = 0;
        }
    }
    cout << rs << endl;
    return 0;
}

Java

import java.util.Scanner;
public class Main {
   
    public static void main(String[] args) {
   
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        int rs = 0;
        char C = s.charAt(0);
        for (int i = 0, w = 0, cnt = 0; i < s.length(); i++) {
   
            w++;
            if (C == s.charAt(i)) cnt++;

            if (cnt > 0 && cnt * 2 == w) {
   
                rs++;
                cnt = 0;
                w = 0;
            }
        }
        System.out.println(rs);
    }
}

Python

s = input()
rs, w, cnt = 0, 0, 0
for c in s:
    w += 1
    if s[0] == c:
        cnt += 1

    if cnt > 0 and cnt * 2 == w:
        rs += 1
        cnt, w = 0, 0

print(rs)

🙏整理题解不易, 如果有帮助到您,请给点个赞 ‍❤️‍ 和收藏 ⭐,让更多的人看到。🙏🙏🙏4

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2023-12-10 21:38:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-10 21:38:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-10 21:38:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-10 21:38:03       18 阅读

热门阅读

  1. 【192】docker在ubuntu系统下常用命令

    2023-12-10 21:38:03       41 阅读
  2. Spring Security OAuth2 认证服务器自定义异常处理

    2023-12-10 21:38:03       38 阅读
  3. Git

    Git

    2023-12-10 21:38:03      34 阅读
  4. vue3+vite动态路由的实现方式

    2023-12-10 21:38:03       48 阅读
  5. netty源码:(6) Future接口

    2023-12-10 21:38:03       32 阅读
  6. 面试冲刺 - 算法题 1

    2023-12-10 21:38:03       38 阅读
  7. 什么是极限编程

    2023-12-10 21:38:03       30 阅读
  8. 第11节: Vue3 动态参数

    2023-12-10 21:38:03       40 阅读
  9. c语言的内存函数

    2023-12-10 21:38:03       36 阅读
  10. 2022蓝桥杯c组求和

    2023-12-10 21:38:03       49 阅读