java 程序题 判断两个字符串是否是同构的

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/whitesun123/article/details/82769837

两个个字符串的每个字母都匹配同一个映射关系,比如egg -> add的映射关系就是:e->a, g->d; foo与bar显然不满足,因为o->a同事o->r;paper和title满足,p->t, a->i, e->l, r->e。现在用map保存映射关系

方法一:

public static boolean isIsomorphic(String s, String t) {
		 
		Map<Character,Integer> map_1 = new HashMap<Character,Integer>();
		Map<Character,Integer> map_2 = new HashMap<Character,Integer>();
		
		if(s.length() != t.length())
			return false;
		
		for(int i = 0;i<s.length();i++){
			if((!map_1.containsKey(s.charAt(i))) && (!map_2.containsKey(t.charAt(i)))){//map全不包含
				map_1.put(s.charAt(i), i);
			    map_2.put(t.charAt(i), i);
			}else if(map_1.containsKey(s.charAt(i)) && map_2.containsKey(t.charAt(i))){//map全部包含
					if(map_1.get(s.charAt(i)) != map_2.get(t.charAt(i)))
						return false;	
				}
			else //一个包含,一个不包含
				return false;
		}
		return true;
	}

方法二:不能判断egg  ddd

public static boolean isIsomorphic_2(String s, String t) {
	      Map <Character,Character> map=new HashMap<Character, Character>();
	      if(s.length()!=t.length()) return false;
	      for(int i=0;i<s.length();i++){
	    	  if(map.containsKey(s.charAt(i))){
	    		 if( map.get(s.charAt(i))!=t.charAt(i)) 
	    			 return false;   
	    	  }else{
	    		  map.put(s.charAt(i), t.charAt(i));
	    	  }
	      }
	      return true;	
	    }

猜你喜欢

转载自blog.csdn.net/whitesun123/article/details/82769837