华为od机试 评论转换输出
最近在刷华为od的题目,HR催的急,估计刷不了两题就直接考了,现在离谱的是我在网上搜的到题目,但是很难搜到免费的答案。
有两年没有上网刷题了,现在互联网已经这么封闭了吗?所有答案都在CSDN,然后所有答案都要买专栏?我都怀疑华为od的HR联合CSDN还收一份卖答案的钱。
太久没写代码了,本来基础也不牢,这种中等难度的题已经觉得头大了,测试想转开发还是太难了。
工作又太忙了,没什么时间刷题,一切随缘吧~
新手推荐一下用VScode,装个CodeGeeX的插件,直接起飞,我都还没想好下一行写啥,这插件就给我补上了,基础不牢直接写注释让插件帮我写,基本不用去查语法了
题目就不写了,是照着这篇的解法改的,原文应该是用python解的,解题思路还挺清晰的,不再重复了
附上链接,感兴趣的自己去看:https://zhuanlan.zhihu.com/p/645573661
下面是我根据上面的python代码改写的C++代码(尝试了一下发现还是python好用,泪目,人生苦短,该选python),不保证对,就尝试了3条示例,基本输出是一致的
#include <iostream> #include <string> #include <queue> #include <vector> #include <stdlib.h> using namespace std; void recursive(queue<string> &q,vector<vector<string>> &v,int level, int childcount); int main() { //输入一个字符串 string str; string strtemp; //输入一个字符串 cin>>str; //创建一个队列 queue<string> q; //将输入的字符串用,分隔 for(int i=0;i<str.length();i++) { if(str[i]==',') { q.push(strtemp); strtemp.clear(); } else { strtemp = strtemp+str[i]; } } q.push(strtemp); //二维vector vector<vector<string>> v; while(q.empty()==false){ string coment = q.front(); q.pop(); if (v.size()==0){ v.push_back(vector<string>()); } int childcount = atoi(q.front().c_str()); q.pop(); v[0].push_back(coment); int level = 2; recursive(q,v,level,childcount); } cout << v.size() << endl; for( int i=0;i<v.size();i++){ for(int j=0;j<v[i].size();j++){ cout<<v[i][j]<<" "; } cout<<endl; } return 0; } //一个递归函数,输入包括队列,数组 void recursive(queue<string> &q,vector<vector<string>> &v,int level, int childcount) { for(int i=0;i<childcount;i++) { string comment = q.front(); q.pop(); if (v.size()<level) { v.push_back(vector<string>()); } v[level-1].push_back(comment); int count = atoi(q.front().c_str()); q.pop(); if(count>0){ recursive(q,v,level+1,count); } } }#牛客解忧铺#