:type dict: List[str] :type sentence: str :rtype: str
(self, dict, sentence)
| 55 | |
| 56 | class Solution(object): |
| 57 | def replaceWords(self, dict, sentence): |
| 58 | """ |
| 59 | :type dict: List[str] |
| 60 | :type sentence: str |
| 61 | :rtype: str |
| 62 | """ |
| 63 | |
| 64 | def judge(dict_word, word): |
| 65 | for i in dict_word: |
| 66 | if not word: |
| 67 | return False |
| 68 | if i == word[0]: |
| 69 | word = word[1:] |
| 70 | continue |
| 71 | return False |
| 72 | return True |
| 73 | |
| 74 | dicts = sorted(dict, key=len) |
| 75 | sentence = sentence.split(' ') |
| 76 | for i, d in enumerate(sentence): |
| 77 | for j in dicts: |
| 78 | if d[0] == j[0]: |
| 79 | if judge(j[1:], d[1:]): |
| 80 | sentence[i] = j |
| 81 | break |
| 82 | |
| 83 | return ' '.join(sentence) |
| 84 | |
| 85 | # 最开始的正则思路,用\s保证一定是root+followed的形式。 |
| 86 | # sentence = ' ' + sentence |