在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given words For each such occurrence, add " Example 1: Input: text = Example 2: Input: text = Note:
给出第一个词 对于每种这样的情况,将第三个词 " 示例 1: 输入:text = "alice is a good girl she is a good student", first = "a", second = "good" 输出:["girl","student"] 示例 2: 输入:text = "we will we will rock you", first = "we", second = "will" 输出:["we","rock"] 提示:
4ms
1 class Solution { 2 func findOcurrences(_ text: String, _ first: String, _ second: String) -> [String] { 3 let subString = first + " " + second 4 let arr = text.split(separator: " ") 5 var result = [String]() 6 for i in 0..<arr.count-2 { 7 if arr[i] == first && arr[i+1] == second { 8 result.append(String(arr[i+2])) 9 } 10 } 11 return result 12 } 13 } Runtime: 8 ms Memory Usage: 21.7 MB
1 import Foundation 2 class Solution { 3 func findOcurrences(_ text: String, _ first: String, _ second: String) -> [String] { 4 if text.isEmpty {return []} 5 var words:[String] = text.components(separatedBy: " ") 6 var list:[String] = [String]() 7 for i in 2..<words.count 8 { 9 if first == words[i-2] && second == words[i-1] 10 { 11 list.append(words[i]) 12 } 13 } 14 return list 15 } 16 } 8ms 1 class Solution { 2 func findOcurrences(_ text: String, _ first: String, _ second: String) -> [String] { 3 var answer: [String] = [] 4 5 var words = Array(text.split(separator: " ")) 6 7 var i = 0 8 9 while (i + 2) < words.count { 10 if words[i] == first, words[i + 1] == second { 11 answer.append(String(words[i + 2])) 12 } 13 14 i += 1 15 } 16 17 return answer 18 } 19 }
|
请发表评论