Leetcode——205-Isomorphic Strings(同构字符串)【待反思周末】
Given two strings s and t, determine if they are isomorphic.给俩字符串,判断是否同构 Two strings are isomorphic if the characters in s can be replaced to get t.同构的判断是:一个字符串中的字符被替换后能得到t,相同字符必须替换的字符也相同 All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. For example, Given "egg", "add", return true. Given "foo", "bar", return false. Given "paper", "title", return true. Note: You may assume both s and t have the same length.
字符串问题,一直就不太明白,也是练得太少了,所以做过一次笔试题就知道自己的欠缺了赶紧来补补,先把easy的弄完
keyword:
相同-----set(不能重复元素)
替换-----hashMap(映射关系)
s的字符对应t中的字符,chars相当于key,chart相当于value,key自带不重复属性,所以要求t的字符不能在Set里面重复
public class Solution { public boolean isIsomorphic(String s, String t) { if(s==null||t==null) return false; if(s.length() != t.length()) return false; Map<Character, Character> map=new HashMap<>(); Set<Character> set=new HashSet<>(); int index=0; char chars,chart; for(;index<s.length();index++) { chars=s.charAt(index); chart=t.charAt(index); //首先判断map里面有没有这个键 //为什么不是先判断set呢,最开始我也想来着,但是作为映射的值,似乎比起key晚一点判断不算什么吧,如果尝试一下流程,发现还是先判断map比较合适 if(!map.containsKey(chars)) { if(!set.contains(chart))//当chars在map中没有,chart还没有被其他的字母映射的时候 { map.put(chars, chart);//就可以放进去啦 set.add(chart); } else return false; } // else { //这时候map里面已经存在映射关系了, if(map.get(chars)!=chart)//相等就继续循环,一旦不相等 return false; } } return true; } }