当前位置:网站首页>Bracket nesting problem (recommended Collection)
Bracket nesting problem (recommended Collection)
2022-07-26 03:40:00 【A boy in the mountains】
Catalog
3、 ... and . Score in parentheses
This article mainly brings you the solution of this bracket nesting problem , For this kind of bracket nesting problem, many old irons may be very headache . Here is a general solution to this kind of problem
Let's take a look at the first question, string decoding :
One . String decoding
1. Corresponding letecode link :
2. Title Description :
3. Their thinking :
Traversal string :
If the current character is a number , namely '0' <= s[i] <= '9' Add this number to the number of times the substring is to be repeated num Because there may be more than one number , So pay attention to the original num Multiply by 10 Add the new figures .
If the current character is an open parenthesis , namely s[i] == '[' Recursion , Notice every recursion num The return value of recursion is the index that has been traversed currently i And substrings ans After getting the return value, you will ans multiply num Add to res in , And reset num.
- If the current character is a closing bracket , namely
s[i] == ']'Returns the current indexiAnd the substring generated during the loop of the current recursive layerresIf the currently traversed letter is directly added to the answer
Let's say "3[a]2[bc]" For example :
First meet 3 Is a number put it in num Just in the middle :
Now come to the left parenthesis to make recursive calls, starting with the next question of the left parenthesis
At this point, the new recursive calling function comes a Location Add it to ans among
Then continue to traverse down to the right bracket. At this time, the end of this recursion tells the place where it is called. The result of this recursion and the traversal to that position
After receiving the recursive result, use num Accumulate the results and add num Set as 0 Calculate from the next position returned by recursion . The following will not be repeated. In fact, they are all the same logic .
4. The corresponding code :
class Solution { public: struct Info { Info(string a, int s) { ans = a; stop = s; } string ans; int stop; }; string decodeString(string s) { return process(s, 0)->ans; } Info* process(const string& str, int index) { string ans;// Record answer int num = 0; // Record the number of occurrences while (str[index] != ']' && index < str.size()) { if (isalpha(str[index])) {// Letter ans += str[index++]; // Just put the letters directly into the answer } else if (isdigit(str[index])) { // Numbers num = num * 10 + str[index] - '0'; index++; } else { // Yes '[' Info* ret = process(str, index + 1); ans += addString(num, ret->ans); num = 0; index = ret->stop + 1;// Calculate from the next position returned recursively } } return new Info(ans, index); } string addString(int num, string str) { string ans; for (int i = 0; i < num; i++) { ans += str; } return ans; } };
Now let's look at a written test question of Tencent, which is very similar to the previous question
Two . Compression algorithm
1. Corresponding OJ link :
Compression algorithm _ tencent 2020 Campus Recruitment - backstage _ Cattle from (nowcoder.com)
2. Title Description :
3. Their thinking
This question is very similar to the previous question. Please see the code for details :
- If the current character is a number , namely '0' <= s[i] <= '9' Add this number to the number of times the substring is to be repeated num Because there may be more than one number , So pay attention to the original num Multiply by 10 Add the new figures .
- If the current character is an open parenthesis , namely s[i] == '[' Recursion , The return value of recursion is the currently traversed index i And substrings ans Get the return value and add it to the current answer
4. The corresponding code :
class Solution { public: /** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * * * @param str string character string * @return string character string */ struct Info { Info(const string&str,int end) { ans=str; stop=end; } string ans; int stop; }; string compress(string str) { // write code here return process(str,0)->ans; } Info*process(const string&str,int index) { string ans;// Record answer int num=0; while(index<str.size()&&str[index]!=']') { if(isalpha(str[index])) { ans+=str[index++]; } else if(isdigit(str[index])) { num=num*10+str[index]-'0'; index++; } else if(str[index]=='|') { index++; } else // Left parenthesis encountered { Info*res=process(str,index+1); ans+=res->ans; index=res->stop+1; } } if(num!=0) { ans= addString(ans,num); } return new Info(ans,index); } string addString(string &str,int num) { string ans; for(int i=0;i<num;i++) { ans+=str; } return ans; } };
3、 ... and . Score in parentheses
1. Corresponding letecode link :
2. Title Description :
3. Their thinking :
- When encountering the left parenthesis, call the recursive function directly
- ans+=max( Result returned by recursive function *2,1)
- Return the answer and calculate to that position
4. The corresponding code
class Solution { public: struct Info { Info(int _score, int _stop) : score(_score) , stop(_stop) {} int score;// score int stop;// Calculate to that position }; int scoreOfParentheses(string s) { return process(s, 0)->score; } Info* process(const string& str, int index) { if (str[index] == ')') {// The right parenthesis returns directly return new Info(0, index); } int ans = 0; // Record scores while (index < str.size() && str[index] != ')') { Info* res = process(str, index + 1); ans += max(2 * res->score, 1);// Compare index = res->stop + 1;// Start with the next question delete res; } return new Info(ans, index); } };
边栏推荐
- 让百度收录,爬虫自己网站
- JS base64编码和解码
- 6-40v input fixed 5V 3.3V output 1.1a current 23-5 package
- Why did Mr. Cao, a productionist in the field of high-end tea, choose Ruifeng L6 max?
- 爆肝出了4W字的Redis面试教程
- Configuration and use of virtualservice, gateway and destinationrule of istio III
- Find My技术|物联网资产跟踪市场规模达66亿美元,Find My助力市场发展
- 【 Kotlin 中的类和对象实例】
- els 窗口设置、WM_CREATE、WM_PAINT
- 【程序员必备】七夕表白攻略:”月遇从云,花遇和风,晚上的夜空很美“。(附源码合集)
猜你喜欢

What are you interviewing for in a big factory? It's worth watching (I)
![[STL]优先级队列priority_queue](/img/79/d13913cbb9d98f936a9501633b38bf.png)
[STL]优先级队列priority_queue

Alibaba Sentinel - 集群流量控制

大厂面试都面试些啥,看了不亏(一)

Navicat connects to MySQL database on Cloud Server

Uncaught TypeError: $(...).onmouseenter is not a function js错误,解决办法:

Derivation of linear regression principle

【 Kotlin 中的类和对象实例】

IDEA2020.3.1不能打开(双击不能打开),但可以通过idea.bat打开。

Why did Mr. Cao, a productionist in the field of high-end tea, choose Ruifeng L6 max?
随机推荐
想要做好软件测试,可以先了解AST、SCA和渗透测试
Why are more and more users of Bing search?
LDP相关知识点
The B2B2C multi merchant system has rich functions and is very easy to open
How Lora wireless gateway can quickly realize end-to-cloud transmission
2022-07-21 第四小组 修身课 学习笔记(every day)
Where can Lora and nb-iot be used
Easyexcel sets row hiding to solve the problem of sethidden (true) invalidation
2022-07-21 study notes of group 4 self-cultivation class (every day)
Mbr3045ct Schottky diode, mbr0100, mbr2060ct diode parameters
MPLS basic experiment configuration
ELS initialization window class
使用anaconda配置gpu版本的tensorflow(30系列以下显卡)
离线数据仓库从0到1-阶段二软件安装
Portable power fast charging scheme 30W automatic pressure rise and fall PD fast charging
div设置高度不生效
LDP related knowledge points
Visio:甘特图如何合并单元格?解决方案:覆盖单元格
2020 AF-RCNN: An anchor-free convolutional neural network for multi-categoriesagricultural pest det
C language preprocessing instructions and makefile script explanation








