题解 | #牛群智能指导系统#
牛群智能指导系统
https://www.nowcoder.com/practice/94e01098fe8f4941ba90fb64ab2d7025
知识点
字符串,哈希
解题思路
题目的意思是根据pattern来看是否匹配plan,比如pattern是abab,那么后面数组的第一个和第三个相同,第二个和第四个相同。
1.根据空格分割字符串plan。
2.遍历pattern,使用map来保存第i个字符的字符串。
3.判断如果之前出现过的字符与之对应的字符串与现在不同则返回false。
4.遍历结束返回true。
Java题解
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pattern string字符串 * @param plan string字符串 * @return bool布尔型 */ public boolean isValidPattern (String pattern, String plan) { String[] arr=plan.split(" "); HashMap<Character,String> map=new HashMap<>(); for(int i=0;i<pattern.length();i++){ char ch=pattern.charAt(i); String s=arr[i]; if(map.get(ch)==null){ map.put(ch,s); }else{ if(!map.get(ch).equals(s)){ return false; } } } return true; } }