給定一個模式,和一個字元串str。傳回str是否符合同樣的模式。
這裡的符合意味着全然的比對,是以這是一個一對多的映射,在pattern中是一個字母。在str中是一個為空的單詞。
比如:
pattern = “abba”。 str = “dog cat cat dog” 應該傳回真。
pattern = “abba”, str = “dog cat cat fish” 應該傳回假。
pattern = “aaaa”, str = “dog cat cat dog” 應該傳回假。
pattern = “abba”, str = “dog dog dog dog” 應該傳回假。
批注:
你可以假定pattern中僅僅包括小寫字母,在str中僅僅包括被單個空格隔開的小寫字母。
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
我發現我真是越來越愛LeetCode了 ……
今天剛做了一道相似的題目:
LeetCode 205 Isomorphic Strings(同構的字元串)(string、vector、map)(*)
僅僅隻是本題是更新版的,之前是字母比對字母。如今是字母比對單詞了。
之前的題目示比例如以下:
當時我們實作了這麼一個函數:
它可以依據字元串生成序列:
如今的需求也是相似的,僅僅隻是更加更新了一點而已:
是以就封裝了例如以下函數:
首先須要對整個長長的字元串進行依據空格進行分割,分割成的單個的字元串并加入到vector數組中。使用了流的相關函數。
後面的部分就和之前的一樣了,由于是個封裝好的函數了,對變量名也進行了一定的改動,前面的那個函數由此改動例如以下:
最後的比較例如以下,由于題目沒有說pattern和str的長度一緻,也就是說假設最後的索引長度不比對了那肯定就是false了。
是以多加一行:
一點半了,大半夜的不睡覺~
沒看之前寫的這篇部落格。隻是思想應該是幾乎相同的~ pattern方面還是一樣,str的話就先構造出一個String數組。然後在HashMap中存儲和推斷String。而不是Char了。