統計最長有效括號個數

  • 很久沒寫博客了,針對之前筆試做的題目,分享一個我的思路,可能在算法空間上不是最佳,希望多家多多指點;
  • 這裏考慮使用vector來實現匹配括號統計,並將成對括號存到vector中,使用棧可以實現同樣的效果,這裏使用vector在擴容上有一定性能損失;
  • 該算法中將第一個括號字符均存入,在最後統計的時候根據最後一個字符來判斷,判決最大括號數目是max還是max-1;
  • 題目主要要求爲:
  • 給定一個只包含 '(' 和 ')' 的字符串,找出最長的包含有效括號的子串的長度。

    示例 1:輸入: "(()" 輸出: 2 解釋: 最長有效括號子串爲 "()"

  • 示例 2:輸入: ")()())" 輸出: 4 解釋: 最長有效括號子串爲 "()()"

  • 算法實現如下:  

      #include<iostream>    
      #include<vector>

      using namespace std;

      int main(){

        int max = 0;
		string str;
		std::getline(std::cin, str);
		const char*pchar = str.c_str();
		vector<char> brc;
		while (*pchar != '\0')
		{
			if (*pchar == '(' || *pchar == ')')
				brc.push_back(*pchar);
			pchar++;
		}

		vector<vector<char>> last;
		vector<char>midch;

		for (auto iter = brc.begin(); iter != brc.end(); iter++)
		{
			if (midch.size() > 0) {
				const auto itx = midch.end() - 1;

				if ((*iter == '('&&*itx == ')') || (*iter == ')'&&*itx == '('))
				{
					midch.push_back(*iter);
					if (iter == brc.end() - 1)
						last.push_back(midch);
				}
				else
				{
					last.push_back(midch);
					midch.clear();
					if (*iter == '(')
						midch.push_back(*iter);
				}
			}
			else
			{
				if (*iter == '(')
					midch.push_back(*iter);
			}
		}

		for (auto it = last.begin(); it != last.end(); ++it)
		{
			if ((*it).size() > max && (*((*it).end() - 1) == ')'))
				max = (*it).size();
			if ((*it).size() > max && (*((*it).end() - 1) == '('))
			{
				max = (*it).size() - 1;
			}
		}
		std::cout << max << endl;
return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章