【LeetCode】205.Isomorphic Strings

来源:互联网 发布:如何查看电脑mac地址 编辑:程序博客网 时间:2024/04/30 03:23

题目:

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.

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.

解答:

使用2个map,分别是s-->t和t-->s,都满足了则为真;

代码:

import java.util.*;public class Solution {    public boolean isIsomorphic(String s, String t) {Map<Character,Character> map1 = new HashMap<Character,Character>(); // map:s -- > tMap<Character,Character> map2 = new HashMap<Character,Character>();// map :t -- > sif(s.length() > 0){char[] schars = s.toCharArray();char[] tchars = t.toCharArray();for(int i=0;i<s.length();i++){char a = schars[i];char b = tchars[i];if(map1.containsKey(a) && map1.get(a)!=b)return false;if(map2.containsKey(b) && map2.get(b)!=a)return false;map1.put(a, b);map2.put(b, a);}}return true;}}



0 0
原创粉丝点击