zoukankan      html  css  js  c++  java
  • 同构字符串

    Leetcode上原题如下:

    给定两个字符串 s 和 t,判断它们是否是同构的。
    
    如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。
    
    所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
    

    第一种思路:哈希表

    建立两个字符串中字母的映射。由于题目要求两个字符不能映射到同一个字符上,因此,建立两个哈希表,前一个哈希表的键值对和后一个哈希表的键值对刚好相反。

    public boolean isIsomorphic(String s, String t){
        if(s.length() != t.length()){
            return false;
        }
        
        Map<Character,Character> map = new HashMap<>();
        Map<Character,Character> antiMap = new HashMap<>();
        
        int len = s.length();
        for(int i = 0; i < len; i++){
            char c = s.charAt(i);
            char r = t.charAt(i);
            if(map.containsKey(c)){
                char value = map.get(c);
                if(value != r){
                    return false;
                }
            }else{
                if(antiMap.containsKey(r))
                    return false;
                else{
                    map.put(c,r);
                    antiMap.put(r,c);
                }
            }
        }
        return true;
    }
    

    第二种思路:查找索引

    public boolean isIsomorphic(String s, String t){
        if(s.length() != t.length())
            return false;
        
        char[] ch1 = s.toCharArray();
        char[] ch2 = t.toCharArray();
        
        int len = s.length();
        for(int i = 0; i < len; i++){
            if(s.indexOf(ch1[i]) != t.indexOf(ch2[i]))
                return false;
        }
        return true;
    }
    
  • 相关阅读:
    程序员的人品
    【转】telnet使用 删除foxmail不能收取的邮件
    35岁以后我在干什么?
    面试
    程序员基本知识数制
    一事无成
    经过XssFilter替换特殊字符后再经zuul路由转发httpEntity缺少内容
    android跳转到市场进行评价 market://search?q
    使用IntelliJ 12.1.12开发android程序
    重定向
  • 原文地址:https://www.cnblogs.com/Chsy/p/11961749.html
Copyright © 2011-2022 走看看