如何判斷乙個字串中的括號是否匹配

2021-09-30 13:10:49 字數 1256 閱讀 8513

描述:給定乙個包含"(",")","[","]"的字串,如果判斷這個字串中的括號是否正確匹配,匹配輸出yes,否則輸出no;

input: [(s)a]

output:yes

**實現一:基於括號數量統計的方法

#include

#include

#include

using namespace std;

bool match(char* str);

int main()

else

cout << "no" << endl;

return 0;

}bool match(char* str)

if (*p==')')

if (*p == '[')

if (*p == ']')

if (count_right_1>count_left_1||count_right_2>count_left_2)

++p;

}if (count_left_1 == count_right_1&&count_left_2 == count_right_2)

else

return false;

}**實現二:基於棧的思想

#include

#include

#include

#include

using namespace std;

int main()

;while (cin >> str)

else

stack.push_back(str[i]);

isbracket = true;

}else if (str[i] == ')')

else

stack.push_back(str[i]);

}else if (str[i] == '[')

else

stack.push_back(str[i]);

}else if (str[i] == ']')

else

stack.push_back(str[i]);}}

if (stack.size() == 0&&isbracket)

else

}return 0;

}**分析:

兩種方法只需要遍歷一次字串,故時間複雜度為o(n);

方法一空間複雜度為o(n),方法二空間複雜度為o(1)

擴充套件:

判斷乙個字串是否在另乙個字串中

方法一 string str1 nihaoksdoksad string str2 ok int total 0 for string tmp str1 tmp null tmp.length str2.length tmp tmp.substring 1 system.out.println st...

判斷乙個字串是否在另乙個字串中

find in set str,str1 判定str是否在str1中有,如果有,則返回其在str1中的位置,如果沒有,返回0 eg select find in set 13教 瀏陽基地,耕耘基地,文淵館,13教,測試基地,耕耘基地 返回4 這個函式有很大的侷限性,他只能判別是否存在於第二個字串中以...

SQL 判斷乙個字串是否在另外乙個字串中

eg str1 admin str2 1234,123admin,xcxx 比較str1是否在str2中 用常用的charindex,返回肯定是有值的,這裡自己動手寫乙個方法 檢查乙個字串是否在另外乙個字串中數,另外乙個字串元素用,隔開 create function dbo checkstrina...