• 205. Isomorphic Strings (Map)


    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.

    思路: 注意本题是一一对应的关系,而hashmap只能保证索引值唯一,即s到t是唯一的,但是可能存在2个s对应同一个t,所以增加了set加以判断

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            int len = s.length();
            if(len == 0) return true;
            
            map<char,char> c_map;
            set<char> c_set; //to avoid two character in s maps to the same character in t
            for(int i = 0; i < len; i++){
                if(c_map.find(s[i]) == c_map.end()){
                    if(c_set.find(t[i]) == c_set.end()){
                        c_map[s[i]] = t[i];
                        c_set.insert(t[i]);
                    }
                    else return false;
                }
                else if(c_map[s[i]]!=t[i]) return false;
            }
            return true;
        }
    };
  • 相关阅读:
    02-高阶函数 map filter sorted
    01-切片的赋值操作
    学习资料记录
    django_初级学习(1)
    git配置使用
    openpyxl操作表格(2)
    openpyxl模块操作excell表格(1)
    精简语法
    MySQL常见面试题
    02-图片转字符画
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5083496.html
Copyright © 2020-2023  润新知