leetcodeWord Pattern
Posted 方寸之间
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcodeWord 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; } }
以上是关于leetcodeWord Pattern的主要内容,如果未能解决你的问题,请参考以下文章
csharp C#代码片段 - 使类成为Singleton模式。 (C#4.0+)https://heiswayi.github.io/2016/simple-singleton-pattern-us
MVC 5 Scaffolder + EntityFramework+UnitOfWork Pattern 代码生成工具