在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string s. Return all the words vertically in the same order in which they appear in s.
Example 1: Input: s = "HOW ARE YOU" Input: s = "TO BE OR NOT TO BE" Input: s = "CONTEST IS COMING" Constraints: 1 <= s.length <= 200 给你一个字符串 s。请你按照单词在 s 中的出现顺序将它们全部竖直返回。
示例 1: 输入:s = "HOW ARE YOU" 输入:s = "TO BE OR NOT TO BE" 输入:s = "CONTEST IS COMING" 提示: 1 <= s.length <= 200 Runtime: 4 ms
Memory Usage: 22 MB
1 class Solution { 2 func printVertically(_ s: String) -> [String] { 3 let aux:[[Character]] = s.components(separatedBy:" ").map{Array($0)} 4 let n:Int = aux.count 5 var ans:[String] = [String]() 6 var c:Int = 0 7 while(true) 8 { 9 var str:String = String() 10 var flag:Int = 0 11 var index:Int = 0 12 for i in 0..<n 13 { 14 if c < aux[i].count 15 { 16 str.append(aux[i][c]) 17 flag = 1 18 index = i 19 } 20 else 21 { 22 str.append(" ") 23 } 24 } 25 if flag == 0{return ans} 26 ans.append(str.subString(0, index + 1)) 27 c += 1 28 } 29 } 30 } 31 32 extension String { 33 // 截取字符串:指定索引和字符数 34 // - begin: 开始截取处索引 35 // - count: 截取的字符数量 36 func subString(_ begin:Int,_ count:Int) -> String { 37 let start = self.index(self.startIndex, offsetBy: max(0, begin)) 38 let end = self.index(self.startIndex, offsetBy: min(self.count, begin + count)) 39 return String(self[start..<end]) 40 } 41 }
|
请发表评论