題目
給你一個字串 s。請你按照單詞在 s 中的出現順序將它們全部豎直返回。
每個單詞只能放在一列上,每一列中也只能有一個單詞。
示例 1:輸入:s = "HOW ARE YOU" 輸出:["HAY","ORO","WEU"]
解釋:每個單詞都應該豎直列印。
"HAY"
"ORO"
"WEU"
示例 2:輸入:s = "TO BE OR NOT TO BE" 輸出:["TBONTB","OEROOE"," T"]
解釋:題目允許使用空格補位,但不允許輸出末尾出現空格。
"TBONTB"
"OEROOE"
" T"
示例 3:輸入:s = "CONTEST IS COMING" 輸出:["CIC","OSO","N M","T I","E N","S G","T"]
提示:1 <= s.length <= 200
s 僅含大寫英文字母。
題目資料保證兩個單詞之間只有一個空格。
解題思路分析1、遍歷;時間複雜度O(n^2),空間複雜度O(n^2)
func printVertically(s string) []string { arr := strings.Split(s, " ") n := len(arr) maxLength := 0 for i := 0; i < n; i++ { if len(arr[i]) > maxLength { maxLength = len(arr[i]) } } temp := make([][]byte, maxLength) for i := 0; i < maxLength; i++ { temp[i] = make([]byte, n) for j := 0; j < n; j++ { temp[i][j] = ' ' } } for i := 0; i < n; i++ { for j := 0; j < len(arr[i]); j++ { temp[j][i] = arr[i][j] } } res := make([]string, 0) for i := 0; i < len(temp); i++ { res = append(res, strings.TrimRight(string(temp[i]), " ")) } return res}
2、遍歷;時間複雜度O(n^2),空間複雜度O(n)
func printVertically(s string) []string { arr := strings.Split(s, " ") n := len(arr) maxLength := 0 for i := 0; i < n; i++ { if len(arr[i]) > maxLength { maxLength = len(arr[i]) } } res := make([]string, 0) for i := 0; i < maxLength; i++ { temp := make([]byte, 0) for j := 0; j < len(arr); j++ { if len(res) < len(arr[j]) { temp = append(temp, arr[j][i]) } else { temp = append(temp, ' ') } } res = append(res, strings.TrimRight(string(temp), " ")) } return res}
總結
Medium題目,遍歷依次填充即可
最新評論