领扣LintCode算法问题答案-1819. 最长双交替子串

    科技2022-08-06  103

    领扣LintCode算法问题答案-1819. 最长双交替子串

    目录

    1819. 最长双交替子串描述样例 1:样例 2:样例 3: 题解鸣谢

    1819. 最长双交替子串

    描述

    给定一个长度为 N 且只包含a和b的字符串 S。你需要找出最长的子串长度,使得其中不包含三个连续的字母。即,找出不包含aaa或bbb的最长子串长度。注意 S 是其本身的子串。

    N 的取值范围是[1,200000];字符串S只包含字符 a 和/或 b.

    样例 1:

    输入: "baaabbabbb" 输出: 7 说明: "aabbabb"是最长符合条件的子串

    样例 2:

    输入: "babba" 输出: 5 说明:整个S符合条件

    样例 3:

    输入: "abaaaa" 输出: 4 说明: "abaa"是最长符合条件的子串

    题解

    public class Solution { /** * @param s: the string * @return: length of longest semi alternating substring */ public int longestSemiAlternatingSubstring(String s) { // write your code here if (s == null || s.length() == 0) { return 0; } int maxCount = 0; int startIndex = 0; char preC = s.charAt(0); int preCount = 1; for (int i = 1; i < s.length(); i++) { char c = s.charAt(i); if (c == preC) { if (preCount == 2) { int count = i - startIndex; if (count > maxCount) { maxCount = count; } startIndex = i - 1; while (i + 1 < s.length() && s.charAt(i + 1) == preC) { i++; startIndex++; } } else { preCount++; } } else { preC = c; preCount = 1; } } int count = s.length() - startIndex; if (count > maxCount) { maxCount = count; } return maxCount; } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.014, SQL: 8