Skip to content

Latest commit

 

History

History
133 lines (102 loc) · 2.48 KB

File metadata and controls

133 lines (102 loc) · 2.48 KB

English Version

题目描述

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

请你返回字符串 s能量

 

示例 1:

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

示例 2:

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

 

提示:

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

解法

Python3

class Solution:
    def maxPower(self, s: str) -> int:
        ans = t = 0
        for i, c in enumerate(s):
            if i == 0 or c == s[i - 1]:
                t += 1
            else:
                t = 1
            ans = max(ans, t)
        return ans

Java

class Solution {
    public int maxPower(String s) {
        int ans = 0, t = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (i == 0 || s.charAt(i) == s.charAt(i - 1)) {
                ++t;
            } else {
                t = 1;
            }
            ans = Math.max(ans, t);
        }
        return ans;
    }
}

C++

class Solution {
public:
    int maxPower(string s) {
        int ans = 0, t = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (i == 0 || s[i] == s[i - 1])
                ++t;
            else
                t = 1;
            ans = max(ans, t);
        }
        return ans;
    }
};

Go

func maxPower(s string) int {
	ans, t := 0, 0
	for i := range s {
		if i == 0 || s[i] == s[i-1] {
			t++
		} else {
			t = 1
		}
		ans = max(ans, t)
	}
	return ans
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

...