isaacpei / algorithm-interview

Weekly algorithm questions for interview
18 stars 0 forks source link

Q001_zzj_solution #3

Open comesx4 opened 6 years ago

comesx4 commented 6 years ago

Question_ID: Q001

Language: csharp

Time Cost: 0 min

Time Complexity: O(n)

Solution

  1. find the index of < > \
  2. judge the order of them
  3. append formated line

My Code

using System;
using System.Text;

namespace XmlFormater
{
    class Program
    {
        static void Main(string[] args)
        {
            string intput = "<a>123<b>456<c/></b></a>";
            Console.WriteLine(Fmt(intput));
            Console.ReadKey();
        }

        static string Fmt(string raw)
        {
            StringBuilder fmt = new StringBuilder();
            int indent = 0;
            int offset = 0;

            while (offset != raw.Length)
            {
                // get special tag index
                var start = raw.IndexOf('<', offset);
                var mid = raw.IndexOf('/', offset);
                var end = raw.IndexOf('>', offset);

                // tag like  </..  means end, decrease indent
                if (start + 1 == mid)
                {
                    indent -= 1;
                }

                // tag like ...< means content before start tag, append the content
                if (offset < start)
                {
                    fmt.Append(' ', indent * 4);
                    fmt.Append($"{raw.Substring(offset, start - offset)}\r\n");
                }

                // append tag with indent
                fmt.Append(' ', indent * 4);
                fmt.Append($"{raw.Substring(start, end - start + 1)}\r\n");

                // tag start, increase indent
                if (mid > end)
                {
                    indent += 1;
                }

                //do offset
                offset = end + 1;
            }

            return fmt.ToString();
        }
    }
}

Other

There is no exception check.

rbee3u commented 6 years ago

思路清晰代码优美命名规范,我辈学习楷模