Longest Substring Without Repeating Characters 最長無重複子串

LeetCode題解 5. Longest Substring Without Repeating Characters

題目

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3.

Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

題目大意:從一個字符串中找到最長無重複的子串。

思路

順序遍歷字符串,用一個map記錄每個字符的出現次數;

當有字符重複時,記錄下從開始位置到當前前一個位置的子串與長度;

在與最長子串進行長度比較,取出最長子串;

清空map,繼續按照之前的位置往下遍歷查找子串。

代碼實現(Go語言)

package main

import (
	"fmt"
)

func main() {
    str := "abcbefd"
    size := len(str)               // 字符串長度
	var maxLength int              // 最大子串長度
	var maxStr string              // 最長子串
    set := make(map[byte]int32, 0) // 用來記錄字符出現次數

	// 循環遍歷字符串
	for i := 0; i < size; i++ {
		var index int // 用來記錄重複字符出現的位置
		for j := i; j < size; j++ {
			// 當字符重複時,記錄位置,退出當前循環
			if set[str[j]] != 0 {
                index = j
				break
			}

			// 沒有重複字符,在map中記錄
            set[str[j]] = 1
		}

		// 如果一直沒有出現重複,說明遍歷到了字符串尾端
		if index == 0 {
            index = size
		}

		// 比較最長子串長度,獲取最長子串
        length := index - i
		if length > maxLength {
            maxLength = length
            maxStr = str[i:index]
		}

		// 清空記錄字符的map,這裏比較暴力,重新申請空間了
        set = make(map[byte]int32, 0)

		// 當剩餘子串長度小於最長子串長度,沒有遍歷下去的必要了,提升效率
		if maxLength >= (size - i) {
			break
		}
	}

    fmt.Println(maxLength, maxStr)
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章