zoukankan      html  css  js  c++  java
  • leetcode 205

    题目描述:

    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.

    Note:
    You may assume both s and t have the same length.

    解法一:

    这是一个很好想的解法,比较好想,但是效率不高,就是一边遍历一边将元素插入map,这样要同时建立s到t的map和t到s的map,同时还要检查不一致,如果出现不一致,则返回false,否则返回true。

    bool isIsomorphic(string s, string t)
    {
        map<char, char> s_map;
        map<char, char> t_map;
    
        for(int i = 0; i < s.size(); i ++)
        {
            if(s_map.find(s[i]) != s_map.end() && s_map.find(s[i])->second != t[i])
                return false;
            else
                s_map[s[i]] = t[i];
            if(t_map.find(t[i]) != t_map.end() && t_map.find(t[i])->second != s[i])
                return false;
            else
                t_map[t[i]] = s[i];
        }
        return true;
    }

    解法二:

    这个解法是我查看其他人的博客看到的,先简单介绍一下算法的思想,这个算法先建立一个对照表,因为char型字符总计128个,所以不用map,也不用unordered_map,而是用一个长度为128的数组来存储对照表,这个对照表仅仅和字符串中字符的位置有关,通过这样的对照表将s和t分别映射到一个新的字符串,满足题目条件的两个字符串应该是在映射后应该相等。

    bool isIsomorphic(string s, string t)
    {
        if(transferStr(s) == transferStr(t))
            return true;
        return false;
    }
    
    string transferStr(string s)
    {
        char temp = '0';
        vector<char> table(128, 0);
        for(int i = 0; i != s.size(); i ++)
        {
            if(table[s[i]] == 0)
                table[s[i]] = temp ++;
            s[i] = table[s[i]];
        }
    
        return s;
    }
  • 相关阅读:
    windows server 2008 R2下如何快速开启远程桌面、1433、telnet
    利用Lambda获取类中属性名称
    EntityFramework之迁移操作(五)
    EntityFramework之多对多关系(四)
    EntityFramework之一对多关系(三)
    EntityFramework之一对一关系(二)
    EntityFramework之创建数据库及基本操作(一)
    Javascript短路表达式
    Javascript中call、apply函数浅析
    Javascript"怪异"现象
  • 原文地址:https://www.cnblogs.com/maizi-1993/p/5894865.html
Copyright © 2011-2022 走看看