2021-03-18: Given a string str, it consists of only two characters:'X' and'.'. 'X' means wall, no lights,

2021-03-18: Given a string str, it consists of only two characters:'X' and'.'. 'X' means wall, no lights can be put on, and no need to be lit,'.' means residential area, lights can be put on but need to be lit. If the light is placed at the i position, the three positions i-1, i and i+1 can be lit. Return if you need to light up all the positions in str that need to be lighted, at least a few lights are needed.

Fu Da's answer 2021-03-18:

1. Count cnt for consecutive points, and then accumulate (cnt+2)/3.
2. Greedy method.

The code is written in golang, the code is as follows:

package main

import "fmt"

func main() {
    str := ".X..XX......."
    ret := minLight1(str)
    fmt.Println("1.对连续的点计数:", ret)
    ret = minLight2(str)
    fmt.Println("2.贪心法:", ret)
}
func minLight1(road string) int {
    roadLen := len(road)
    i := 0
    light := 0

    cnt := 0
    for i < roadLen {
        if road[i] == 'X' {
            light += (cnt + 2) / 3
            cnt = 0
        } else {
            cnt++
        }
        i++
    }
    light += (cnt + 2) / 3

    return light
}

func minLight2(road string) int {
    roadLen := len(road)
    i := 0
    light := 0
    for i < roadLen {
        if road[i] == 'X' {
            i++
        } else {
            light++
            if i+1 == roadLen {
                break
            } else {
                if road[i+1] == 'X' {
                    i = i + 2
                } else {
                    i = i + 3
                }
            }
        }
    }
    return light
}

The execution results are as follows:
Insert picture description here


comment

Guess you like

Origin blog.51cto.com/14891145/2665048