• 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;
    }
  • 相关阅读:
    (转)ios限制控制器旋转
    iOS NSMutableURLRequest 上传图片
    iOS中UIWebView使用JS交互
    Cocoa pods的安装和使用
    NSThread/NSOperation/GCD 三种多线程技术
    动画效果-基础动画设置(改变大小,改变透明度,翻转,旋转,复原)
    动画效果一风火轮加载效果/动态图展示
    Swift代理和传值
    Swift基础(类,结构体,函数)
    IOS面试问题总结
  • 原文地址:https://www.cnblogs.com/maizi-1993/p/5894865.html
Copyright © 2020-2023  润新知