isaacpei / algorithm-interview

Weekly algorithm questions for interview
18 stars 0 forks source link

Q001_HHPLow_solution #6

Open HHPLow opened 6 years ago

HHPLow commented 6 years ago

Question_ID: Q001

Language: C

Time Cost: ∞

Time Complexity: O(n)

Solution

  1. First... only parse '<' '>' '/'
  2. Then... output other and add enter and space
  3. And... Is ok

My Code

#include <stdio.h>

void parse_xml(char *src_xml)
{
    int count = 0;
    int i = 0;
    int is_end = 0;

    while (src_xml[i]) {
        switch (src_xml[i]) {
            case '<':
                if (i != 0)
                    printf("\n");
                for(int j =0; j < count; j++)
                    printf("    ");
                printf("<");
                count++;
                break;
            case '>':
                printf(">");
                if (!is_end) {
                    printf("\n");
                    for(int j=0; j<count; j++)
                        printf("    ");
                } else {
                    is_end = 0;
                    count--;
                }
                break;
            case '/':
                is_end = 1;
                count--;
                printf("/");
                break;
            default:
                printf("%c", src_xml[i]);
                break;
        }
        i++;
    }
    printf("\n");
}

int main(int argc, char *argv[])
{
    parse_xml(argv[1]);
    return 0;
}

Other

菜鸟,希望dalao们多指教. Thx.

ryanorz commented 6 years ago

这道题如果不考虑错误输入处理的话,用状态机写起来会比较复杂。不考虑错误处理,根据 '<' 找到 '>' 写起来会容易一些。

isaacpei commented 6 years ago

首先仰慕写c的, 写c的都是大佬... 然后我觉得吧... 思路似乎有点小错误最好修正一下, 楼主自己先找几个test case试试?