当前位置:网站首页>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); } };
边栏推荐
- Matlab paper illustration drawing template issue 39 - stairs
- Three ways of redis cluster
- Dominate the salary list! What industry has a "money" path?
- 让百度收录,爬虫自己网站
- DDD landing is called an advanced
- LoRa和NB-IOT可用用在哪些地方
- Portable power fast charging scheme 30W automatic pressure rise and fall PD fast charging
- els 注册窗口类、创建窗口类、显示窗口
- 78. Subset
- 中国数据库 OceanBase 入选 Forrester Translytical 数据平台报告
猜你喜欢

多商户商城系统功能拆解15讲-平台端会员标签

TCP experimental verification

Looking at the next step of BAIC bluevale through the 8billion fund-raising, product upgrading and building core capabilities are the key words

Multi merchant mall system function disassembly lecture 15 - platform side member label
![[stl] priority queue priority_ queue](/img/79/d13913cbb9d98f936a9501633b38bf.png)
[stl] priority queue priority_ queue

6年从零开始的自动化测试之路,开发转测试我不后悔...

sersync/lsync实时同步

Uncaught TypeError: $(...). Onmousenter is not a function JS error, solution:

MPLS基础实验配置

Easyexcel sets row hiding to solve the problem of sethidden (true) invalidation
随机推荐
Uncaught TypeError: $(...). Onmousenter is not a function JS error, solution:
Hcip day 8 notes sorting (OSPF routing control, Appendix E, anti ring, shortest path calculation, republication))
Navicat连接云端服务器上的MySQL数据库
离线数据仓库从0到1-阶段二软件安装
Use eventlog analyzer for log forensics analysis
Hurry in!!! Write a number guessing game with dozens of lines of code based on the basic knowledge of C language
PXE efficient batch network installation
els 消息循环
[stl] priority queue priority_ queue
Bing(必应)搜索,为什么用户越来越多?
PHP连接mysql数据库,数据库连接静态工具类,简化连接。
els 修改光标、修改图标
[virtualization] view the log files of vCenter and esxi hosts
Use VRRP technology to realize gateway equipment redundancy, with detailed configuration experiments
Istio三之VirtualService、Gateway、DestinationRule配置使用
C language preprocessing instructions and makefile script explanation
How Lora wireless gateway can quickly realize end-to-cloud transmission
Div setting height does not take effect
2022-07-21 study notes of group 4 self-cultivation class (every day)
ue4如何进行静态渲染?5个步骤生成静态渲染








