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 "foo", "app"; returns true we can map f -> a and o->p
    given "bar", "foo"; returns false we can't map both 'a' and 'r' to 'o'

    given "ab", "ca"; returns true we can map 'a' -> 'b' and 'c' -> 'a'

    Solution 1: one map

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            if(s.size()!=t.size())return false;
            map<char, char> m;
            for(int i=0;i<s.size();i++){
                if(!m.count(s[i])){
                    map<char,char>::const_iterator iter=m.begin();
                    while(iter!=m.end()){
                        if(iter->second==t[i])return false;
                        iter++;
                    }
                    m.insert(make_pair(s[i], t[i]));
                }else{
                    if(m[s[i]]!=t[i])return false;
                }
            }
            return true;
        }
    };

    Solution 2: two map

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            if(s.size()!=t.size()) return false;  
            map<char,char> ms, mt;
            for(int i=0;i<s.size();i++)
            {  
                char c1=s[i], c2=t[i];  
                if(ms.count(c1)) 
                    if(ms[c1]!=c2)return false;  
                if(mt.count(c2))  
                    if(mt[c2]!=c1)return false;  
                ms.insert(make_pair(c1, c2));  
                mt.insert(make_pair(c2, c1));  
            }  
            return true;  
        }
    };
  • 相关阅读:
    用SQL语言操作数据
    用表组织数据
    第一个C#程序
    利用CSS3制作网页动画
    CSS3美化网页元素
    列表、表格与媒体元素
    表单
    HTML5基础
    使用Java编译思想
    Day06:方法 / 猜字母游戏
  • 原文地址:https://www.cnblogs.com/irun/p/4796061.html
Copyright © 2011-2022 走看看