Featured image of post 1446. 连续字符

1446. 连续字符

题目描述

给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。 请你返回字符串的能量。

示例 1:

1
2
3
输入:s = "leetcode"
输出:2
解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。

示例 2:

1
2
3
输入:s = "abbcccddddeeeeedcba"
输出:5
解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。

示例 3:

输入:s = “triplepillooooow”

输出:5

示例 4:

1
2
输入:s = "hooraaaaaaaaaaay"
输出:11

示例 5:

1
2
输入:s = "tourist"
输出:1

提示:

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

解法一:一次遍历

MY CODE

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    int maxPower(string s) {
        int n = s.size();
        if (1 == n)
            return 1;
        int ans = 0;
        int t = 1;
        for (int i = 1; i < n; ++i) {
            if (s[i] != s[i-1]) {
                ans = max(ans, t);
                t = 1;
            } else {
                ++t;
            }
        }
        return max(ans, t);
    }
};

Official Answer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    int maxPower(string s) {
        int ans = 1, cnt = 1;
        for (int i = 1; i < s.length(); ++i) {
            if (s[i] == s[i - 1]) {
                ++cnt;
                ans = max(ans, cnt);
            } else {
                cnt = 1;
            }
        }
        return ans;
    }
};

复杂度分析

  • 时间复杂度:$O(n)$,其中 $n$ 是字符串 $s$ 的长度。遍历一次 $s$ 的时间复杂度为 $O(n)$。
  • 空间复杂度:$O(1)$。我们只需要常数的空间保存若干变量。

作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/consecutive-characters/solution/lian-xu-zi-fu-by-leetcode-solution-lctm/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计