【Brush questions diary】385. Mini parser

Get into the habit of writing together! This is the 13th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the event details .

【Brush questions diary】385. Mini parser

The 33rd article of this brushing diary, the title is: [ brushing diary] 385. Mini parser , medium

1. Topic description:

Come back early on Friday and continue to brush the daily question, and resolutely do not fall

At first glance at this question, I don't know what I'm talking about. It doesn't seem to be difficult. If you have confidence in yourself, let's read it carefully.

2. What idea does this question examine? What is your thinking?

Let's carefully confirm what this problem requires us to do:

  • Given a string in the title, we need to convert it into an object given in the title
type NestedInteger struct {
}
复制代码
  • The requirements of the title are very clear, but how do we need to achieve it? Let's take a closer look at the examples given in the title.

At a glance, we probably know that the NestedInteger object itself can contain an integer , or it can contain 1 integer + 1 NestedInteger sub-object

Carefully analyze the situation of this NestedInteger :

We drew a sketch with the example given in the title, and we found that the string given by the title is actually nested NestedInteger objects.

So for this kind of nested problem, can we easily think of a recursive way, that is, the depth-first algorithm, first recurse to the deepest, and then go up layer by layer

There is also a general point, we need to look at the member methods of the NestedInteger object given in the question

To solve this problem, we can use the above member methods, we will use

  • SetInteger , for setting an integer into an object
  • Add , for adding child objects NestedInteger

The main logic of this question is to use the depth-first algorithm to traverse the given string, recursively, when encountering '[', go deeper into one layer, encounter ']' and exit this layer, encounter ' ,' means that the current object has 2 elements

Through the above disassembly, the idea should be very clear , and the rest is to implement our code

3. Coding

According to the above logic and analysis, we can translate it into the following code, which requires great attention:

  • Recursive way, pay attention to '[' and ']'
  • Pay attention to the case of 1 element or 2 elements in the object, pay attention to the comma
  • Watch out for negative numbers

The encoding is as follows:

func deserialize(s string) *NestedInteger {
    // 初始化索引,从 0 开始
    index := 0
    // 定义递归函数
    var dfs func() *NestedInteger
    dfs = func()*NestedInteger{
        // 我们需要开始创建一个新的对象  *NestedInteger , 这个对象,里面包含数字和列表,也可以只有数字
        nes := &NestedInteger{}
        // 1 校验当前的位置是否需要递归创建新对象
        if s[index] == '['{
            // 向后偏移一位
            index++
            // 只要当前这一位对应的字符 不是 ] ,则就会开始创建对象
            for s[index] != ']'{
                nes.Add(*dfs())
                // 递归出来之后,校验到当前位置是 , 字符,那么说明,当前  NestedInteger 对象是有数字和列表,需要跳过,,继续遍历
                if s[index] == ','{
                    index++
                }
            }
            // 程序能走到这里,说明已经找到 [] 了 , 需要 index 继续 +1,对出本轮递归,向上捅的时候,要往后偏移,上层递归直接判断字符即可
            index++
            return nes
        }

        // 2 在当前对象中,读取数字
        // 先确定一下数字的符号是否是负数
        fushu := (s[index] == '-')
        if fushu {
            // 如果是负数,那么咱们记录一下,然后索引向后偏移
            index++
        }

        nums := 0
        // 此处的循环控制需要注意,我们知道整数是连续的,遇到 逗号,或者[  ] 我们就认为一个整数遍历完成
        for ; index < len(s) && unicode.IsDigit(rune(s[index])); index++ {
            nums = nums*10 +  int(s[index] - '0')
        }
        // 校验是否需要添加负号
        if fushu {
            nums = -nums
        }

        nes.SetInteger(nums)
        return nes
    }

    return dfs()
}
复制代码

After reading the above ideas and coding, as well as the comments in the coding, I believe that it is easier to understand, and the code is more clearly presented.

4. Summary:

Here we can see that we have only traversed the s string once, so the time complexity is O(n)

What is the space complexity here? Xmd can think about it

Original title address: 385. Mini Parser

I am here today, what I have learned, if there are any deviations, please correct me

Welcome to like, follow, favorite

Friends, your support and encouragement are the motivation for me to persist in sharing and improve quality

Okay, here it is this time

Technology is open, and our mentality should be open. Embrace change, live in the sun, and move forward.

I'm the little devil boy Nezha , welcome to like, follow and collect, see you next time~

Guess you like

Origin juejin.im/post/7086846151822934024