为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode1065. 字符串的索引对 | Index Pairs of a String

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10961676.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given a text string and words (a list of strings), return all index pairs [i, j] so that the substring text[i]...text[j] is in the list of words.

Example 1:

Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
Output: [[3,7],[9,13],[10,17]]

Example 2:

Input: text = "ababa", words = ["aba","ab"]
Output: [[0,1],[0,2],[2,3],[2,4]]
Explanation: 
Notice that matches can overlap, see "aba" is found in [0,2] and [2,4]. 

Note:

  1. All strings contains only lowercase English letters.
  2. It's guaranteed that all strings in words are different.
  3. 1 <= text.length <= 100
  4. 1 <= words.length <= 20
  5. 1 <= words[i].length <= 50
  6. Return the pairs [i,j] in sorted order (i.e. sort them by their first coordinate in case of ties sort them by their second coordinate).

给出 字符串 text 和 字符串列表 words, 返回所有的索引对 [i, j] 使得在索引对范围内的子字符串 text[i]...text[j](包括 i 和 j)属于字符串列表 words。
示例 1:

输入: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
输出: [[3,7],[9,13],[10,17]]
示例 2:

输入: text = "ababa", words = ["aba","ab"]
输出: [[0,1],[0,2],[2,3],[2,4]]
解释:
注意,返回的配对可以有交叉,比如,"aba" 既在 [0,2] 中也在 [2,4] 中
提示:

 1.所有字符串都只包含小写字母。
  2.保证 words 中的字符串无重复。
  3.1 <= text.length <= 100
  4.1 <= words.length <= 20
  5.1 <= words[i].length <= 50
  6.按序返回索引对 [i,j](即,按照索引对的第一个索引进行排序,当第一个索引对相同时按照第二个索引对排序)。


Runtime: 92 ms

Memory Usage: 21.4 MB

 1 class Solution {
 2     func indexPairs(_ text: String, _ words: [String]) -> [[Int]] {
 3         var ret:[[Int]] = [[Int]]()
 4         let arrText:[Character] = Array(text)
 5         for word in words
 6         {
 7             let arrStr:[Character] = Array(word)
 8             let num:Int = arrStr.count
 9             for i in 0..<arrText.count
10             {
11                 if (arrText[i] == arrStr.first!) && (i + num <= arrText.count) && (Array(arrText[i..<(i + num)]) == arrStr)
12                 {
13                     ret.append([i,i + num - 1])
14                 }
15             }
16         }
17         ret.sort(){
18             if $0[0] == $1[0]
19             {
20                 return $0[1] <= $1[1]
21             }
22             else
23             {
24                 return $0[0] <= $1[0]
25             }
26         }
27         return ret
28     }
29 }

 

posted @ 2019-06-02 00:32  为敢技术  阅读(674)  评论(0编辑  收藏  举报