首页 » C++ » 205. Isomorphic Strings

205. Isomorphic Strings

原文 http://blog.csdn.net/u010665216/article/details/76397676

2017-07-30 18:20:09阅读(681)

题目:

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.

思路:

本题通过哈希表映射的实现来实现,要s到t的映射及t到s的映射

代码:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s.size()!=t.size())
            return false;
        map<char,char> mp;
        for(int i =0;i<s.size();i++)
        {
            if(mp.find(s[i])==mp.end())
                mp[s[i]] = t[i];
            else if(mp[s[i]]!=t[i])
                return false;
        }
        mp.clear();
        for(int i =0;i<s.size();i++)
        {
            if(mp.find(t[i])==mp.end())
                mp[t[i]] = s[i];
            else if(mp[t[i]]!=s[i])
                return false;
        }
        return true;
    }
};


最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹