• 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; 
        }
    }
    

      

  • 相关阅读:
    webpack 5 之持久化缓存
    前端资源加载失败优化
    如何用 JS 实现二叉堆
    简单解析一下扫码登陆原理,简单到你想不到!
    实战:Express 模拟 CSRF 攻击
    Yarn 的 Plug&#39;n&#39;Play 特性
    为什么现在我更推荐 pnpm 而不是 npm/yarn?
    小米3移动版刷安卓6.0-小米手机3 移动版 Flyme 6.7.11.24R beta
    小米5手机最后一版安卓6.0 MIUI8 6.11.10 小米5s手机最后一版安卓6.0 MIUI8 7.6.8
    vim格式转换
  • 原文地址:https://www.cnblogs.com/Cherrylalala/p/6550827.html
Copyright © 2020-2023  润新知