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

Go 复制代码
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)
}
相关推荐
逐光沧海21 小时前
数据结构-链表习题(C++)
数据结构·c++·链表
老师我太想进步了20262 天前
【数据结构-12】树与二叉树的结构、概念
数据结构
2601_967980112 天前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
zaizai10072 天前
算法(左程云)2
数据结构
漂流瓶jz2 天前
UVA-1615 高速公路 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·贪心算法·贪心·aoapc·算法竞赛入门经典·uva
夊2 天前
数据结构第四课:栈与队列
数据结构
凌冰_2 天前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
郝学胜-神的一滴3 天前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
console.log('npc')3 天前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
郝学胜-神的一滴3 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl