最长匹配{}的长度
题目描述
设计算法,实现任意输入一个仅包含字符“{”和“}”的字符串,输出最长的匹配的“{”和“}”子串长度。
要求:
该子串的内容全部是匹配的“{”和“}”。
例如:“{{{}{{}}”,其输出结果为6,而非8,“{}{{}}”是符合要求的最长匹配子串;
“{{{}}}”输出6;
“{{}}}”输出4;
“{}}”输出2;
代码
#include <iostream>
#include <string>
using namespace std;
int longestMatch(string s)
{
int num = 0;
int nLeftChar = 0;
for(int i=0;i<s.length(); i++)
{
switch(s[i])
{
case '{':
nLeftChar++;
break;
case '}':
if(nLeftChar)
{
nLeftChar--;
num++;
break;
}
}
}
return num;
}
int main()
{
string s;
cin>>s;
cout<<longestMatch(s);
return 0;
}

6005

被折叠的 条评论
为什么被折叠?



