Word pattern

Topic:
Given a pattern and a string str, judge whether str follows the same rule.

Follow here refers to complete matching. For example, there is a bidirectional connection between each letter in the pattern and each non-empty word in the string str.
Insert picture description here

Analysis:

The idea of ​​using a hash table.

Let's think and analyze first:
Insert picture description here
So the idea is:
Insert picture description here
For example:
Insert picture description here

Code:

class Solution {
    
    
    public boolean wordPattern(String pattern, String s) {
    
    
     Map<String, Character> word_map = new HashMap<String, Character>();  //单词到pattern字符的映射
     int[] used=new int[128];  //已被映射的pattern字符
     String word="";//保存临时的pattern字符
     int pos=0;  //当前指向的pattern字符
     s=s+" ";  //s尾部增加一个空格,以便遇到空格拆分单词
     for(int i=0;i<s.length();i++){
    
    
         if(s.charAt(i)==' '){
    
       //遇到空格,即拆分出一个单词
              if(pos==pattern.length()){
    
       //若分割出一个单词,却无pattern字符对应
                  return false;
              }
              if(word_map.get(word) == null){
    
       //单词未出现在哈希映射中
                 if(used[pattern.charAt(pos)]!= 0){
    
     //如果当前pattern字符已使用
                     return false;
                 }
                 word_map.put(word, pattern.charAt(pos));
                //  word_map[word]=pattern.charAt(pos);
                 used[pattern.charAt(pos)]=1;

              }else{
    
    
                   if(word_map.get(word)!=pattern.charAt(pos)){
    
     //若当前word已建立映射,无法与当前pattern对应
                       return false;
                   }
              }
              word="";  //完成一个单词的插入和查询后,清空word
              pos++;
         }else{
    
    
             word+=s.charAt(i); 
         }
     }
     if(pos!=pattern.length()){
    
       //还有多余的pattern字符
         return false;
     }
     return true;
    }
    }

Source: LeetCode
Link: https://leetcode-cn.com/problems/word-pattern
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_42120561/article/details/114497441
Recommended