zoukankan      html  css  js  c++  java
  • 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.

    判断2个字符串是否同构,思路:可先将字符串转换成abc的形式,若同构则转换后的字符串应该相等,代码如下:

    public class Solution {
        
        /**
         * 将字符串转换成abc的形式如egg->abb,paper->abacd
         */
        public String transform(String s) {
            StringBuffer re = new StringBuffer("");
            char tmp = 'a';
            Map<Character,Character> map = new HashMap<Character,Character>();
            for(int i=0;i<s.length();i++) {
                if(!map.containsKey(s.charAt(i))) {
                    map.put(s.charAt(i),tmp);
                    re.append(tmp);
                    tmp++;
                }
                else {
                    re.append(map.get(s.charAt(i)));
                }
            }
            return re.toString();
        }
        
        public boolean isIsomorphic(String s, String t) {
            if(transform(s).equals(transform(t))) return true;
            else return false;
        }
    }
  • 相关阅读:
    shell编程介绍
    第一章作业
    jenkins介绍与操作
    gitlab介绍与操作
    github介绍与操作
    git介绍与操作
    zabbix监控tomcat与安全规范
    js-20170605-基本语法
    webstorm激活方法
    mac的一些基本设置(分享篇)
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4465236.html
Copyright © 2011-2022 走看看