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;
    }
  • 相关阅读:
    记录软件工程课程项目开发时遇到的各种小问题(django)
    用python实现逻辑回归
    利用KD树进行异常检测
    PyQt4入门学习笔记(五)
    PyQt4入门学习笔记(四)
    import matplolib 时出现"This probably means that tk wasn't installed properly."的解决方法
    IDEA上安装和使用checkstyle,findbugs,visualVM,PMD插件
    pycharm连接mysql数据库
    基于trie树做一个ac自动机
    用python实现最长公共子序列算法(找到所有最长公共子串)
  • 原文地址:https://www.cnblogs.com/maizi-1993/p/5894865.html
Copyright © 2011-2022 走看看