题解 | #农场智能分类系统#
农场智能分类系统
https://www.nowcoder.com/practice/a2c9a3fce4f141a3956fe67cd00cc3e2
知识点
字符串
解题思路
这道题的意思是在字符s和t中s的一个字符对应t的一个字符,当s中有一个字符对应t的多个字符就返回“no”,同理t也是。
因此,肯定要保证他们字符串长度是相等的。
定义两个map保存他们相互之间的对应关系,当某次s对应上了而t没有对应上,或者t对应上了s没有对应上,就返回“no”。
Java题解
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param t string字符串 * @return string字符串 */ public String isIsomorphic (String s, String t) { if(s.length()!=t.length()) return "NO"; HashMap<Character,Character> map=new HashMap(); for(int i=0;i<s.length();i++){ char ch1=s.charAt(i); char ch2=t.charAt(i); if(map.get(ch1)==null&&map.get(ch2)!=null){ return "NO"; }else if(map.get(ch1)!=null&&map.get(ch2)==null){ return "NO"; }else{ map.put(ch1,ch2); map.put(ch2,ch1); } } return "YES"; } }