[Swift]LeetCode1181. 前后拼接 | Before and After Puzzle
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a list of? A?phrase?is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are?no consecutive spaces?in a phrase. Before and After?puzzles?are phrases that are formed by merging?two phrases where the?last?word of the first?phrase?is the same as the?first word of the second phrase. Return the?Before and After?puzzles that can be formed by every two phrases? You should return a list of?distinct?strings?sorted?lexicographically. ? Example 1: Input: phrases = ["writing code","code rocks"] Output: ["writing code rocks"] Example 2: Input: phrases = ["mission statement","a quick bite to eat",? "a chip off the old block",? "chocolate bar",? "mission impossible",? "a man on a mission",? "block party",? "eat my words",? "bar of soap"] Output: ["a chip off the old block party",? "a man on a mission impossible",? "a man on a mission statement",? "a quick bite to eat my words","chocolate bar of soap"] Example 3: Input: phrases = ["a","b","a"] Output: ["a"] ? Constraints:
? 给你一个「短语」列表? 「短语」(phrase)是仅由小写英文字母和空格组成的字符串。「短语」的开头和结尾都不会出现空格,「短语」中的空格不会连续出现。 「前后拼接」(Before and After?puzzles)是合并两个「短语」形成「新短语」的方法。我们规定拼接时,第一个短语的最后一个单词?和?第二个短语的第一个单词?必须相同。 返回每两个「短语」? 注意,两个「短语」拼接时的顺序也很重要,我们需要同时考虑这两个「短语」。另外,同一个「短语」可以多次参与拼接,但「新短语」不能再参与拼接。 请你按字典序排列并返回「新短语」列表,列表中的字符串应该是?不重复的?。 ? 示例 1: 输入:phrases = ["writing code","code rocks"] 输出:["writing code rocks"] 示例 2: 输入:phrases = ["mission statement",? "a chip off the old block",? "chocolate bar",? "mission impossible",? "a man on a mission",? "block party",? "eat my words",? "bar of soap"] 输出:["a chip off the old block party",? "a man on a mission impossible",? "a man on a mission statement",? "a quick bite to eat my words","chocolate bar of soap"] 示例 3: 输入:phrases = ["a","a"] 输出:["a"] ? 提示:
Runtime:?112 ms
Memory Usage:?23.5 MB
1 class Solution { 2 func beforeAndAfterPuzzles(_ phrases: [String]) -> [String] { 3 var map:[String:[Int]] = [String:[Int]]() 4 var i:Int = 0 5 for str in phrases 6 { 7 let first:String = str.components(separatedBy:" ").first! 8 map[first,default:[Int]()].append(i) 9 i += 1 10 } 11 i = 0 12 var res:Set<String> = Set<String>() 13 for str in phrases 14 { 15 let array:[String] = str.components(separatedBy:" ") 16 let last = array.last! 17 if map[last] != nil 18 { 19 let arr:[Int] = map[last]! 20 for index in arr 21 { 22 if index == i {continue} 23 res.insert(str + phrases[index].subString(last.count)) 24 } 25 } 26 i += 1 27 } 28 return Array(res).sorted(by:<) 29 } 30 } 31 32 extension String { 33 // 截取字符串:从index到结束处 34 // - Parameter index: 开始索引 35 // - Returns: 子字符串 36 func subString(_ index: Int) -> String { 37 let theIndex = self.index(self.endIndex,offsetBy: index - self.count) 38 return String(self[theIndex..<endIndex]) 39 } 40 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |