Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
Example 3:
Input: s = "triplepillooooow"
Output: 5
Example 4:
Input: s = "hooraaaaaaaaaaay"
Output: 11
Example 5:
Input: s = "tourist"
Output: 1
Constraints:
1 <= s.length <= 500
s contains only lowercase English letters.
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.AskGif.Easy.String
{
public class MaxPowerSoln
{
public int MaxPower(string s)
{
if (s.Length == 0) return 0;
int max = 1;
int count = 1;
for(int i=1; i<s.Length; i++)
{
if (s[i - 1] == s[i])
{
count++;
}
else
{
if(count>max)
{
max = count;
}
count = 1;
}
}
if (count > max)
{
max = count;
}
return max;
}
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Unit Tests:
using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingUnitTest.Easy.String
{
[TestClass]
public class MaxPowerSolnTests
{
[TestMethod]
public void MaxPowerSoln_First()
{
var s = "leetcode";
var output = 2;
var res = new MaxPowerSoln().MaxPower(s);
Assert.AreEqual(res, output);
}
[TestMethod]
public void MaxPowerSoln_Second()
{
var s = "abbcccddddeeeeedcba";
var output = 5;
var res = new MaxPowerSoln().MaxPower(s);
Assert.AreEqual(res, output);
}
[TestMethod]
public void MaxPowerSoln_Third()
{
var s = "triplepillooooow";
var output = 5;
var res = new MaxPowerSoln().MaxPower(s);
Assert.AreEqual(res, output);
}
[TestMethod]
public void MaxPowerSoln_Fourth()
{
var s = "hooraaaaaaaaaaay";
var output = 11;
var res = new MaxPowerSoln().MaxPower(s);
Assert.AreEqual(res, output);
}
[TestMethod]
public void MaxPowerSoln_Fifth()
{
var s = "tourist";
var output = 1;
var res = new MaxPowerSoln().MaxPower(s);
Assert.AreEqual(res, output);
}
[TestMethod]
public void MaxPowerSoln_Sixth()
{
var s = "cc";
var output = 2;
var res = new MaxPowerSoln().MaxPower(s);
Assert.AreEqual(res, output);
}
}
}



