题目表述:
给你一个只包含字符 'a'
,'b'
和 'c'
的字符串 s
,你可以执行下面这个操作(5 个步骤)任意次:
- 选择字符串
s
一个 非空 的前缀,这个前缀的所有字符都相同。 - 选择字符串
s
一个 非空 的后缀,这个后缀的所有字符都相同。 - 前缀和后缀在字符串中任意位置都不能有交集。
- 前缀和后缀包含的所有字符都要相同。
- 同时删除前缀和后缀。
请你返回对字符串 s
执行上面操作任意次以后(可能 0 次),能得到的 最短长度 。
示例 1:
输入:s = "ca" 输出:2 解释:你没法删除任何一个字符,所以字符串长度仍然保持不变。
示例 2:
输入:s = "cabaabac" 输出:0 解释:最优操作序列为: - 选择前缀 "c" 和后缀 "c" 并删除它们,得到 s = "abaaba" 。 - 选择前缀 "a" 和后缀 "a" 并删除它们,得到 s = "baab" 。 - 选择前缀 "b" 和后缀 "b" 并删除它们,得到 s = "aa" 。 - 选择前缀 "a" 和后缀 "a" 并删除它们,得到 s = "" 。
示例 3:
输入:s = "aabccabba" 输出:3 解释:最优操作序列为: - 选择前缀 "aa" 和后缀 "a" 并删除它们,得到 s = "bccabb" 。 - 选择前缀 "b" 和后缀 "bb" 并删除它们,得到 s = "cca" 。
提示:
1 <= s.length <= 100000
s
只包含字符'a'
,'b'
和'c'
。
解题思路:
while循环条件是字符串s的最后一个字符和首字符相同。
while中的条件语句是将前缀相同的字符和后缀相同的字符找出删除。
如果剩余s的长度等于1,则直接return 1;
如果字符串的首字符和最后字符不同,return字符串s的长度。
解题代码(99/100,最后一个案例没有通过):
class Solution {
public:
int minimumLength(string s) { //最后一个用例通过不了
while(s[0]==s[s.length()-1])
{
if(s.length()==1)
return 1;
int start=0;
int end=s.length()-1;
while(start<s.length()&&s[start]==s[0])
{
start++;
}
while(end>=0&&s[end]==s[s.length()-1])
{
end--;
}
if(end<start)
{
return 0;
}
else
{
s=s.substr(start);
s=s.substr(0,end-start+1);
}
}
return s.length();
}
};
解题代码:
class Solution { //官方题解
public:
int minimumLength(string s) {
int n = s.size();
int left = 0, right = n - 1;
while (left < right && s[left] == s[right]) {
char c = s[left];
while (left <= right && s[left] == c) {
left++;
}
while (left <= right && s[right] == c) {
right--;
}
}
return right - left + 1;
}
};