首页 > 代码库 > leetcode(一)Word Pattern
leetcode(一)Word Pattern
题目描述:
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.
本人思路:把字符串转化为字符串数组后,先比较长度;再用pattern里的字符替换掉字符串。全部替换后再重新转化为字符串,并与pattern字符串相比较,得出结论。
代码如下(C#):
public bool WordPattern(string pattern, string str) { //char[] patternAttr=new char[pattern.Length] char[] patternAttr=pattern.ToCharArray(); string[] strAttr=str.Split(‘ ‘); if(patternAttr.Length!=strAttr.Length) { return false; } else { for(int i=0;i<strAttr.Length;i++) { for(int j=i;j<strAttr.Length;j++) { if(strAttr[j]==strAttr[i]) { strAttr[j]=patternAttr[i].ToString(); } strAttr[i]=patternAttr[i].ToString(); } } str=String.Join("",strAttr); if(str==pattern)return true; else return false; } }
leetcode(一)Word Pattern
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。