栈相关的算法
- 平衡符号
- 中缀到后缀表达式的转换。
- 递归函数的使用。具体见https://blog.csdn.net/ychhh/article/details/80305197
栈算法相关的练习题
-
练习一:
题目要求:给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为:k[encoded_string]
,表示其中方括号内部的encoded_string正好重复k次。注意k保证为正整数。你可以认为输入字符串总是有效的。输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。此外你可以认为原始数据不包含数字,所有的数字只表示重复的次数k,例如不会出现像?3a?
或?2[4]?
的输入。示例如下:s = "3[a]2[bc]", 返回 "aaabcbc"
s = "3[a2[c]]", 返回 "accaccacc"
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef"
int StringParse(const char *pBuff,char *pOut,int outBufflen) { const char *pStr = pBuff; char *pTempBuff = NULL; int stackIndex = 0; pTempBuff = (char *)malloc(outBufflen); if(pTempBuff == NULL){ return -1; } //程序中应该实时判断是否超出outBufflen长度,为简单,未判断。 while(*pStr != '\0'){ if(*pStr == ']'){ int tempIndex = stackIndex - 1; while(pOut[tempIndex] != '['){//向前查找匹配符 tempIndex --; } int byteNum = 1; int num = pOut[tempIndex - 1] - '0';//此处只做了数字为0~9的情况 int size = stackIndex - tempIndex - 1;//重复字符个数 //printf("num(%d) size(%d)\n",num,size); memcpy(pTempBuff,&pOut[tempIndex + 1],size); stackIndex = tempIndex - byteNum; for(int j = 0; j < num; j++){//将解析后的数据压栈 for(int k = 0; k < size; k++){ pOut[stackIndex++] = pTempBuff[k]; } } pStr++; } else{ pOut[stackIndex++] = *pStr; pStr++; } } pOut[stackIndex] = '\0'; free(pTempBuff); return 0; } void main(void) { char *strBuff[3] = {"1[2]12[bc]","3[a12[c]]","2[abc]3[cd]ef"}; const int outBuffSize = 256; char outBuff[outBuffSize]; for(int i = 0; i < 3; i++){ printf("input str:%s\n",strBuff[i]); StringParse(strBuff[i],outBuff,outBuffSize); printf("parse str:%s\n \n",outBuff); } }
关于技术交流
此处后的文字已经和题目内容无关,可以不看。
qq群:825695030
微信公众号:嵌入式的日常
如果上面的文章对你有用,欢迎打赏、点赞、评论。