• [Microsoft] Intealeaving of two given strings, Solution


    Desgin an algorithm to find whether a given sting is formed by the Intealeaving of two given strings.
      For example,
    stringA: ABCEF...
    string B: ABCA...

    dst string : ABCABCEF....

    [Thoughts]
    Brute-force
    1:  /* a simple brute force solution */  
    2: int isInterleaving(char* a, char* b, char* c, int ai, int bi, int ci)
    3: {
    4: printf("entry info: %d, %d, %d,\n", ai, bi, ci);
    5: if (a[0]=='\0' && b[0]=='\0' && c[0]=='\0')
    6: return 1;
    7: if (b[0]=='\0' && a[0]=='\0' && c[0]!='\0')
    8: return 0;
    9: int tmp1=0;
    10: int tmp2=0;
    11: if (a[0]!='\0' && a[0]==c[0])
    12: tmp1 = isInterleaving(a+1, b, c+1, ai+1, bi, ci+1);
    13: if (tmp1 == 1)
    14: return 1;
    15: if (b[0]!='\0' && b[0]==c[0])
    16: tmp2 = isInterleaving(a, b+1, c+1, ai, bi+1, ci+1);
    17: printf("res: %d %d %d\n", tmp1, tmp2, (tmp1 | tmp2));
    18: return tmp1 | tmp2;
    19: }

    Dynamic programming method: Consider a rectangle network of m*n, where m is the length of a and n is the length of b. Label the rows using characters in string a and cols using characters in string b. 
    All that you need to do is to find a path from the top left corner to the bottom right corner. This at most requires you to examine m*n states, which gives you m*n time complexity. (Assume top left is (0, 0), then element[i][j] is a boolean which means whether there is a path from (0, 0) to (i, j) that covers the first i+j characters in the target.)
    1:  int isInterleavingdp(char* a, char* b, char* str, int alen, int blen)  
    2: { int i, j;
    3: int m[alen+1][blen+1];
    4: memset(m, 0, (alen+1)*(blen+1)*sizeof(int));
    5: for(i=0; i<alen; i++)
    6: {
    7: if (a[i]==str[i])
    8: m[i+1][0]=1;
    9: else
    10: break;
    11: }
    12: for(j=0; j<blen; j++)
    13: {
    14: if (b[j] == str[j])
    15: m[0][j+1]=1;
    16: else
    17: break;
    18: }
    19: for(i=1; i<=alen; i++)
    20: {
    21: for(j=1; j<=blen; j++)
    22: {
    23: int r1 = (m[i-1][j]>0) && a[i-1]==str[i+j-1];
    24: int r2 = (m[i][j-1]>0) && b[j-1]==str[i+j-1];
    25: m[i][j] = r1 | r2;
    26: }
    27: }
    28: for(i=0; i<=alen; i++)
    29: {
    30: for(j=0; j<=blen; j++)
    31: {
    32: printf("%d ", m[i][j]);
    33: }
    34: printf("\n");
    35: }
    36: return m[alen][blen];
    37: }
  • 相关阅读:
    The Node.js Event Loop, Timers, and process.nextTick()
    Main event loop
    Why should I avoid blocking the Event Loop and the Worker Pool?
    HTML Standard系列:Event loop、requestIdleCallback 和 requestAnimationFrame
    在这个示例中,使用 watch 选项允许我们执行异步操作 (访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这些都是计算属性无法做到的。
    多线程 主线程
    mvvm
    跨库事务
    nginx 死循环
    nginx proxy pass redirects ignore port
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078906.html
Copyright © 2020-2023  润新知