Problem · String

Longest Same-Character Substring

Learn this problem
EasyCapital OneFULLTIMEOA

Problem statement

You are given a string source consisting of lowercase English letters. Find the longest contiguous substring that consists of one repeated character. If several substrings have the same maximum length, choose the rightmost one.

Return a string made from that character followed by the length of the chosen substring.

Note: You are not expected to provide the most optimal solution, but a solution with time complexity not worse than O(source.length^3) will fit within the execution time limit.

Function

longestSameCharacterSubstring(source: String) → String

Examples

Example 1

source = "bbacccdbbab"return = "c3"
  • There are two contiguous substrings consisting of the character "a", both have a length of 1.
  • There are three contiguous substrings consisting of the character "b", two have a length of 2 and one has a length of 1.
  • There is just one contiguous substring consisting of the character "c", which has a length of 3. So, this is the longest contiguous substring and hence the answer is "c3".

Example 2

source = "bbaacaa"return = "a2"

There are three different contiguous substrings with a length of 2, so the answer should be the rightmost one — "a2".

Constraints

  • 1 <= source.length <= 100
  • source contains only lowercase English letters.

More Capital One problems

drafts saved locally
public String longestSameCharacterSubstring(String source) {
  // write your code here
}
source"bbacccdbbab"
expected"c3"
checking account