[Java] 290. Word law-understand the separator of a string! ! !

Given a regular pattern and a string str, judge whether str follows the same pattern.

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.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:

Input: pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

public static boolean wordPattern(String pattern, String s) {
    
    
		String [] str=s.split(" ");
		if(pattern.length()!=str.length) {
    
    
			return false;
		}
		for(int i=0;i<pattern.length()-1;i++) {
    
    
			for(int j=i+1;j<pattern.length();j++) {
    
    
				if(pattern.charAt(i)==pattern.charAt(j)) {
    
    
					if(!str[i].equals(str[j])) {
    
    
						return false;
					}
				}else {
    
    
					if(str[i].equals(str[j])) {
    
    
						return false;
					}
				}
			}
		}
		
		return true;

    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/111245005