zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    python基础--文件操作实现全文或单行替换
    python基础7--集合
    python读写json文件
    python基础6--目录结构
    python基础5--模块
    Ubuntu的一些常用快捷键
    ubuntu dpkg 命令详解
    linux(Ubuntu)安装QQ2013
    fcitx-sogoupinyin下载地址和安装
    Ubuntu下装QQ2014
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5083496.html
Copyright © 2011-2022 走看看