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.

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.

我一开始的思路是只要两个字符串有重复的字母的位置是一样的就是符合要求的,于是写了如下代码

class Solution {
    public boolean isIsomorphic(String s, String t) {
      if(s.length()!=t.length()){
          return false;
      }
        char[]s1=s.toCharArray();
        char[]t1=t.toCharArray();
        for(int i=0;i<s1.length;i++){
            for(int j=i;j<s1.length;j++){
                if(s1[i]==s1[j]&&t1[i]!=t1[j]){
                    return false;
                }
                if(t1[i]==t1[j]&&s1[i]!=s1[j]){
                    return false;
                }
            }
        }
        return true;
    }

时间超时了。。。看大神的解法自愧不如。。。
字符串的问题常用字典和HashMap来解决,下面两个解法都很巧妙

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s == null || s.length() <= 1) return true;
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        for(int i = 0 ; i< s.length(); i++){
            char a = s.charAt(i);
            char b = t.charAt(i);
            if(map.containsKey(a)){
                 if(map.get(a).equals(b))
                continue;
                else
                return false;
            }else{
                if(!map.containsValue(b))
                map.put(a,b);//看ab是不是一一对应
                else return false;

            }
        }
        return true;

    }
}
public class Solution {
    public boolean isIsomorphic(String s1, String s2) {
        int[] m = new int[512];//相当于建立一个字典
        for (int i = 0; i < s1.length(); i++) {
            if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
            m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
            //记录位置信息
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/srping123/article/details/77648941