leetcode 290 Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

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.

Notes:

  1. patterncontains only lowercase alphabetical letters, and str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters.
  2. Both pattern and str do not have leading or trailing spaces.
  3. Each letter in pattern must map to a word with length that is at least 1.

public class Solution {
    public boolean wordPattern(String pattern, String str) {
         String[] strarray=str.split(" "); 
	     char[] pattern_array = pattern.toCharArray( );
	    
	     int [] st = new int[strarray.length];
	     int [] pa = new int[pattern_array.length];
	     
	     int s = 1;
	     for (int i = 0; i < strarray.length; i++) {
	    	 for (int j = i; j< strarray.length; j++){
	    		 if(strarray[i].compareTo(strarray[j]) == 0){
	    			 if(st[j] == 0)
	    				 st[j] = s;
	    		 }
	    	 }
	    	 s++;
	    	 if(Arrays.binarySearch(st,0) < 0)
	    		 break;			 
	     }
	     s = 1;
	     for (int i = 0; i < pattern_array.length; i++) {
	    	 for (int j = i; j< pattern_array.length; j++){
	    		 if(pattern_array[i] == pattern_array[j]){
	    			 if(pa[j] == 0)
	    				 pa[j] = s;
	    		 }
	    	 }
	    	 s++;
	    	 if(Arrays.binarySearch(pa,0) < 0)
	    		 break;			     
	     }
    	 if(Arrays.equals(st, pa))
	    	 return true;
    	 else
	    	return false;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章