日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

面试题整理12 求字符串括号最大深度子串

發布時間:2025/3/21 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 面试题整理12 求字符串括号最大深度子串 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:求一個表達式字符串中括號層次最深的第一個表達式,如表達式 

"a+b+((c+d)+(e+f))",則結果為”c+d"。

分析: 一般算式會讓人想起用棧分別存儲操作數和符號值,但是本題目不適用,我寫的代碼中采用了類似于求最大連續子數組的解法,設置變量一個記錄當前的括號深度,一個記錄最大的括號深度,從字符串頭開始遍歷,當遍歷到字符‘('時,當前括號深度加1,當遍歷到字符‘)'時,當前括號深度減1,;當當前括號深度大于最大括號深度時,將當前括號深度賦值給最大括號深度;當當前括號深度小于0時,將當前括號深度置0。算法復雜度O(n)。

代碼如下:如有錯誤,請大家指正。


char* FindMostDeepExpression(const char* str) {if(str == NULL)return NULL;int nLength = strlen(str);if(nLength < 2)return (char*)str;int maxDeepNum = 0;int tempDeepNum = 0;int startIndex = 0;int endIndex = nLength-1;bool isEnd = false; //標志是結束for(int i=0; i<nLength; ++i){if(str[i] == '('){++tempDeepNum;if(tempDeepNum > maxDeepNum ){maxDeepNum = tempDeepNum;isEnd = false;startIndex = i+1;}}else if( str[i] == ')'){if( tempDeepNum == maxDeepNum && !isEnd){endIndex = i-1;isEnd = true;}-- tempDeepNum;if(tempDeepNum < 0){tempDeepNum = 0;}}}char *result = new char[endIndex-startIndex+2];strncpy(result,str+startIndex,endIndex-startIndex+1);result[endIndex-startIndex+1] = '\0';return result; } void Test(char *testName, char* str,char* expectResult) {if( testName!= NULL)printf("%s begins:\n",testName);if(expectResult != NULL)printf("expected result is %s \n",expectResult);char* result = FindMostDeepExpression(str);printf("the actual result is : %s \n",result);} void Test1() {char* str = NULL;Test("Test1",str,NULL); } void Test2() {char* str = "a+b";Test("Test2",str,"a+b"); } void Test3() {char* str = "a+b+((c+d)+(e+f))";Test("Test3",str,"c+d"); } void Test4() {char* str = "a+b+((c+d)+(e+f))";Test("Test3",str,"c+d"); } void Test5() {char* str = "a+(b+c)";Test("Test5",str,"b+c"); } int main() {Test1();Test2();Test3();Test4();system("pause"); }

總結

以上是生活随笔為你收集整理的面试题整理12 求字符串括号最大深度子串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。