1. 程式人生 > >leetcode Isomorphic Strings

leetcode Isomorphic Strings

Isomorphic Strings  題目:https://leetcode.com/problems/isomorphic-strings/

同構字串:

建立一個map 實現一個字串到另一個字串的對映,用set儲存第二個字串,避免出現多對一。

public static void main(String[] args) {
//		String s="egg";
//		String t="add";
		String s="foo";
		String t="bar";
		boolean isomorphic = isIsomorphic(s, t);
		System.out.println(isomorphic);

	}

	public static boolean isIsomorphic(String s, String t) {
		Map<Character,Character> map=new HashMap<>();
		Set<Character> set=new HashSet<>();
		if(s.length()!=t.length()){
			return false;
		}
		for(int i=0;i<s.length();i++){
			char c = s.charAt(i);
			char d = t.charAt(i);
			if(map.containsKey(c)){
				if(map.get(c)==d){

				}else{
					return false;
				}
			}else{
				if(set.contains(d)){
					return false;
				}else{
					map.put(c,d);
					set.add(d);
				}
			}
		}
		return true;
	}