首页 > 学院 > 开发设计 > 正文

205. Isomorphic Strings

2019-11-08 02:19:24
字体:
来源:转载
供稿:网友

题目

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.

Subscribe to see which companies asked this question.


思路

搞两个hashmap,分别做对应char到数字的映射,数字从1开始,再遍历两个string判断


代码

class Solution {public: bool isIsomorphic(string s, string t) { //思路,搞两个hashmap,分别做对应char到数字的映射,数字从1开始 map<char,int> mapS; map<char,int> mapT; int numS = 1; int numT = 1; if(s.size() != t.size()) { return false; } for(size_t i = 0;i < s.size();i++) { //map中都没找到 if(mapS.find(s.at(i)) == mapS.end() && mapT.find(t.at(i)) == mapT.end()) { mapS[s[i]] = numS; numS++; mapT[t[i]] = numT; numT++; continue; } //有一个找不到,返回false if(mapS.find(s.at(i)) == mapS.end() || mapT.find(t.at(i)) == mapT.end()) { return false; } //都找到了 if(mapS[s[i]] != mapT[t[i]]) { return false; } } return true; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表