zoukankan      html  css  js  c++  java
  • Isomorphic Strings

    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.

    思路:

      读懂题意后,简单的映射问题而已 Hashmap

    我的代码:

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            if(s==null && t==null)  return true;
            if(s==null || t==null || s.length()!=t.length())    return false;
            int len = s.length();
            HashMap<Character,Character> oneToTwo = new HashMap<Character,Character>();
            HashMap<Character,Character> twoToOne = new HashMap<Character,Character>();
            
            for(int i=0; i<len; i++)
            {
                char a = s.charAt(i);
                char b = t.charAt(i);
                if(oneToTwo.containsKey(a))
                {
                    char tmp = oneToTwo.get(a);
                    if(b != tmp)    return false;
                }
                else
                    oneToTwo.put(a, b);
                if(twoToOne.containsKey(b))
                {
                    char tmp = twoToOne.get(b);
                    if(a != tmp)    return false;
                }
                else
                    twoToOne.put(b, a);
            }
            return true;
        }
    }
    View Code

    他人代码:

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            char[] map1 = new char[256], map2 = new char[256];
            for (int i = 0; i < s.length(); i++) {
                char a = s.charAt(i);
                char b = t.charAt(i);
                if (!this.map(a, b, map1) || !this.map(b, a, map2)) { return false; }
            }
            return true;
        }
    
        private boolean map(char a, char b, char[] map) {
            if (map[a] == 0) { map[a] = b; }
            return map[a] == b;
        }
    }
    View Code

    学习之处:

      对于char类型的hashmap问题,为什么为什么不用数组非得用hashmap呢,下次应该注意常用char数组,而非hashmap

  • 相关阅读:
    转char varchar nvarchar区别
    NHibernate和Spring.Net框架介绍(一)
    ASP.NET面试题(一)
    存储过程编写经验和优化措施
    软件工程师不可不知的10个概念
    优化数据库前问自己的10个问题
    ZOJ 1610 Count the Colors (线段树)
    POJ 3667 Hotel (线段树)
    HDU Best Reward (扩展KMP)
    POJ 3277 City Horizon (线段树)
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4479185.html
Copyright © 2011-2022 走看看