1446. 连续字符『简单』

题目来源于力扣(LeetCode

一、题目

1446. 连续字符

题目相关标签:字符串

提示:

  • 1 <= s.length <= 500
  • s 只包含小写英文字母。

二、解题思路

  1. 遍历字符数组,判断当前字符是否与前一个字符相同

  2. 相同时,记录出现的次数变量加 1

  3. 不同时,将本次出现的次数与已记录的出现次数做比较,取最大值,并将记录出现的次数变量重置为 1

三、代码实现

public static int maxPower(String s) {
    int ans = 0;
    int count = 1;
    // 字符串转字符数组操作
    char[] arr = s.toCharArray();
    // 遍历数组,找到最长的连续的相同字符的个数
    for (int i = 1; i < arr.length; i++) {
        // 当前遍历元素与前一个元素相同时,次数加 1
        if (arr[i] == arr[i - 1]) {
            count += 1;
        } else {
            // 当前遍历元素与前一个元素不同时,比较连续的个数与已记录的最大连续个数
            ans = Math.max(ans, count);
            // 重置次数为 1
            count = 1;
        }
    }
    // 最后的元素为连续字符时,循环中未处理,做最后的判断
    return Math.max(ans, count);
}

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    String s = "leetcode";  // output:2
//    String s = "abbcccddddeeeeedcba";  // output:5
//    String s = "triplepillooooow";  // output:5
//    String s = "hooraaaaaaaaaaay";  // output:11
//    String s = "tourist";  // output:1

    int result = maxPower(s);
    System.out.println(result);
}
posted @ 2020-06-09 21:41  知音12138  阅读(506)  评论(0编辑  收藏  举报