【华为OD机试真题】78、去除多余空格(200分)

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type keywordPosition struct {
	start int
	end   int
}

func str2slice(str string) []string {
	length := len(str)
	list := make([]string, length)
	for i, i2 := range str {
		list[i] = string(i2)
	}
	return list
}

func tidyKeywordPositionStr(str string) []*keywordPosition {
	keywordPositions := strings.Split(str, ",")
	list := make([]*keywordPosition, 0)
	for _, positionStr := range keywordPositions {

		tempPositionArray := strings.Split(positionStr, " ")
		start, _ := strconv.Atoi(tempPositionArray[0])
		end, _ := strconv.Atoi(tempPositionArray[1])
		item := &keywordPosition{
			start: start,
			end:   end,
		}
		list = append(list, item)
	}
	return list
}

func main() {
	var inputStr, keywordPositionStr string
	scanner := bufio.NewScanner(os.Stdin)
	if scanner.Scan() {
		inputStr = scanner.Text()
	}
	if scanner.Scan() {
		keywordPositionStr = scanner.Text()
	}

	inputStrSlice := str2slice(inputStr)
	KeywordPositions := tidyKeywordPositionStr(keywordPositionStr)

	newStrSlice := make([]string, 0)
	//是否为但括号区域
	isJump := false

	for i, r := range inputStrSlice {
		if !isJump && r == "'" {
			isJump = true
		}

		if isJump {
			newStrSlice = append(newStrSlice, r)

			if r == "'" {
				isJump = false
			}
			continue
		}

		//出现需要删除的空格下标
		tempIndex := -1

		if r == " " {
			//上一个是不是空格
			if i > 0 {
				if inputStrSlice[i-1] != r {
					newStrSlice = append(newStrSlice, r)
				} else {
					tempIndex = i
				}
			}
		} else {
			newStrSlice = append(newStrSlice, r)
		}

		//更新原来关键词的索引
		if tempIndex > -1 {
			for i2, position := range KeywordPositions {
				if tempIndex <= position.start {
					position.start--
					position.end--
				}
				if tempIndex > position.start && tempIndex <= position.end {
					position.end--
				}
				KeywordPositions[i2] = position
			}
		}

	}

	//输出
	fmt.Println(strings.Join(newStrSlice, ""))
	outPutPositionStr := ""
	for _, position := range KeywordPositions {
		outPutPositionStr = fmt.Sprintf("%s[%d, %d]", outPutPositionStr, position.start, position.end)
	}
	fmt.Println(outPutPositionStr)
}

上一篇:【畅捷通-注册安全分析报告】


下一篇:大数据笔记之 Hadoop 常用 Shell 命令(一)