栈与队列 3 - 2020-4-13/17- 算法题

170 阅读5分钟

算法题

  • 括号匹配检验

  • a.将第0个元素压栈
  • b.遍历字符范围[1,strlen(data)]
  • c.取栈顶字符
  • d.检查该括号是左括号
    • 左:判断后面字符data[i]是右括号 YES 入栈/ NO 出栈
  • e.遍历结束,如果栈为空就匹配成功
//链式栈
int ExecuteData(SqStack stack,char* data){
    Push(&stack,data[0]);
    for(int i=1;i<strlen(data);i++){
        char top = GetTop(stack);
        switch(top){
            case '(':
                if(data[i] == ')') Pop(&stack);
                else Push(&stack,data[i]);
                break;
            case '[':
                if(data[i]==']') Pop(&stack);
                else Push(&stack,data[i]);
                break;
            case '#':
                if(data[i]=='(' || data[i] =='['){
                    Push(&stack,data[i]);
                    break;
                }
                default:
                return -1;
                break;
        }
        
    }
    if(stack.top == stack.base) {
        Destroy(&stack);
        return 0; // 0 means NoError
    }esle{
        Destroy(&stack);
        return -1;
    }
    return 0;
}
  • 进制转换
void conversion(int N){
    SqStack S;
    SElemType e;
    InitStack(&S);
    while(N){
        PushData(&S,N%8);
        N = N/8;
    }
    while(!StackEmpty(S)){
        Pop(&S,&e);
        printf("%d\n",e);
    }
}
  • 每日气温

/*
 暴力法1:
 1. 从左到右开始遍历,从第一个数到最后一个数开始遍历. 最后一个数因为后面没有元素,默认是0,不需要计算;
 2. 从[i+1,TSize]遍历,每个数直到找到比它大的数,数的次数就是对应的值;
 */
int  *dailyTemperatures_1(int* T, int TSize, int* returnSize){
    
    int *result = (int *)malloc(sizeof(int) * TSize);
    *returnSize = TSize;
    result[TSize-1] = 0;
    
    for(int i = 0;i < TSize-1;i++)
        if(i>0 && T[i] == T[i-1])
            result[i] = result[i-1] == 0?0:result[i-1]-1;
        else{
            for (int j = i+1; j < TSize; j++) {
                if(T[j] > T[i]){
                    result[i] = j-i;
                    break;
                }
                if (j == TSize-1) {
                    result[i] = 0;
                }
            }
        }
    
    return result;
}
/*
 跳跃对比:
 1. 从右到左遍历. 因为最后一天的气温不会再升高,默认等于0;
 2. i 从[TSize-2,0]; 从倒数第二天开始遍历比较. 每次减一;
 3. j 从[i+1,TSize]遍历, j+=result[j],可以利用已经有结果的位置进行跳跃,从而减少遍历次数
 -若T[i]<T[j],那么Result = j - i;
 -若reuslt[j] == 0,则表示后面不会有更大的值,那么当前值就应该也是0;
 
 */

int *dailyTemperatures_2(int* T, int TSize, int* returnSize){
    
    int *result = (int *)malloc(sizeof(int) * TSize);
    *returnSize = TSize;
    result[TSize-1] = 0;
    
    for (int i=TSize-2; i >= 0; i--) {
        for (int j = i+1; j < TSize; j+=result[j]) {
            if (T[i] < T[j]) {
                result[i] = j-i;
                break;
            }else
            {
                if (result[j] == 0) {
                    result[i] = 0;
                    break;
                }
            }
        }
    }
    
    return result;
}

/*
 思路:
 1. 初始化一个栈(用来存储索引),value数组
 1. 栈中存储的是元素的索引值index;
 2.将当前元素和栈顶元素比较;
    如果栈为空,那么直接将当前元素索引index 存储到栈中;
    如果栈顶元素>当前元素,则将当前元素索引index 存储到栈中;
    如果栈顶元素<当前元素,则将当前元素索引index-栈顶元素index,计算完毕则将当前栈顶元素移除,将当前元素索引index 存储到栈中

 */
int* dailyTemperatures_3(int* T, int TSize, int* returnSize) {
    
    int* result = (int*)malloc(sizeof(int)*TSize);
    // 用栈记录T的下标。
    int* stack_index = malloc(sizeof(int)*TSize);
    *returnSize = TSize;
    // 栈顶指针。
    int top = 0;
    int tIndex;
    
    for (int i = 0; i < TSize; i++)
        result[i] = 0;
    
    for (int i = 0; i < TSize; i++) {
        printf("\n循环第%d次,i = %d\n",i,i);
       
        // 若当前元素大于栈顶元素,栈顶元素出栈。即温度升高了,所求天数为两者下标的差值。
        while (top > 0 && T[i] > T[stack_index[top-1]]) {
            tIndex = stack_index[top-1];
            result[tIndex] = i - tIndex;
            top--;
            printf("tIndex = %d; result[%d] = %d, top = %d \n",tIndex,tIndex,result[tIndex],top);
        }
        
        // 当前元素入栈。
        stack_index[top] = i;
        printf("i= %d;  StackIndex[%d] = %d ",i,top,stack_index[top]);
        top++;
        
        printf(" top = %d \n",top);
    }
    
    return result;
}

  • 爬楼梯问题

//递归思路
/*
    f(n) = f(n-1)+f(n-2)
    f(1) = 1;
    f(2) = 2;
*/
int ClimbStairs_1(int n){
    if(n<1) return 0;
    if(n ==1) return 1;
    if(n == 2) return 2;
    return ClimbStaris_1(n-1) + ClimbStairs_1(n-2);
}

//动态规划解法

    
  • 去除重复字母

int ClimbStairs(int n){
    if(n==1) return 1;
    int temp = n+1;
    int *sum = (int *)malloc(sizeof(int) * (temp));
    sum[0] = 0;
    sum[1] = 1;
    sum[2] = 2;
    
    for (int i = 3; i <= n; i++) {
        sum[i] = sum[i-1] + sum[i-2];
    }
    
    return sum[n];
}
  • 字符串编码

/*
思路
12[a]为例
1.遍历字符串s
2.当前字符不为“】” 入栈;
3.当前字符为“】” 则: ① 复制字符 stack="12【a",‘a'
② 找到备份的数量: 为空/上限栈顶,下限是数字
③ "12\0"转为整形数字12
④ copy a 复制12份
⑤ 字符串加'\0'作为结束符
 */

char * decodeString(char * s){
   
    /*.
     1.获取字符串长度
     2.设置默认栈长度50
     3.开辟字符串栈(空间为50)
     4.设置栈头指针top = -1;
     */
    int len = (int)strlen(s);
    int stackSize = 50;
    char* stack = (char*)malloc(stackSize * sizeof(char));
    int top = -1;
    
    //遍历字符串,在没有遇到"]" 之前全部入栈
    for (int i = 0; i < len; ++i) {
        if (s[i] != ']') {
            //将字符入栈stack
            stack[++top] = s[i];
        }
        else {
            int tempSize = 10;
            char* temp = (char*)malloc(tempSize * sizeof(char));
            int topOfTemp = -1;
            
            while (stack[top] != '[') {
                ++topOfTemp;
                temp[topOfTemp] = stack[top];
                //stack出栈,则top栈顶指针递减;
                top--;
            }
            
            //找到倍数数字.strOfInt字符串;
            char strOfInt[11];
            int curTop = top;
            top--;
            while (top != -1 && stack[top] >= '0' && stack[top] <= '9') {
                top--;
            }
            for (int j = top + 1; j < curTop; ++j) {
                strOfInt[j - (top + 1)] = stack[j];
            }
            //为字符串strOfInt数组加一个字符结束后缀'\0'
            strOfInt[curTop - (top + 1)] = '\0';

            //把字母复制strOfInt份到stack中去;
            int curNum = atoi(strOfInt);
            for (int k = 0; k < curNum ; ++k) {
                
                int kk = topOfTemp;
                while (kk != -1) {

                    ++top;
                    stack[top] = temp[kk];
                    kk--;
                    
                }
            }
            free(temp);
            temp = NULL;
        }
    }
    
    //realloc 动态内存调整;
    //void *realloc(void *mem_address, unsigned int newsize);
    //构成字符串stack后, 在stack的空间扩容.
    char* ans = realloc(stack, (top + 1) * sizeof(char));
    ans[++top] = '\0';
    
    //stack 栈不用,则释放;
    free(stack);
    return ans;
}
  • 杨辉三角
/*
 思路:
 1. 第一层循环控制行数i : 默认[i][0] = 1,[i][i] = 1
 2. 第二层循环控制列数j : triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
 */
/*
    返回一个指针数组 所以要用到**
*/
int** generate(int numRows,int * returnSize){
    *returnSize = numRows;
    int **res = (int **)malloc(sizeof(int*)*numRows);
    for(int i=0;i<numRows;i++){
        res[i] =(int *)malloc(sizeof(int)*(i+1));
        res[i][0] = 1;
        res[i][i] = 1;
        for(int j=1;j<i;j++){
            res[i][j] = res[i-1][j] + res[i-1][j-1];
        }
    }
    return res;
}