• [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: }
  • 相关阅读:
    Ajax
    通过浏览器渲染过程来进行前端优化
    渲染树结构、布局和绘制
    JS 和 CSS 的位置对其他资源加载顺序的影响
    Linq中dbSet 的查询
    如何在windows“我的电脑”中添加快捷文件夹
    SQL Server中2008及以上 ldf 文件过大的解决方法
    出现“初始化数据库时发生异常”解决办法
    MVC使用ajax取得JSon数据
    asp.net mvc 使用Ajax调用Action 返回数据【转】
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078906.html
Copyright © 2020-2023  润新知