码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode(一)Word Pattern

时间:2016-12-16 01:05:18      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:span   dog   思路   ++   should   pre   ring   string   题目   

题目描述:

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:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. 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

标签:span   dog   思路   ++   should   pre   ring   string   题目   

原文地址:http://www.cnblogs.com/dayang12525/p/6185368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!