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

leecode 解题总结:205. Isomorphic Strings

2019-11-08 00:45:09
字体:
来源:转载
供稿:网友
#include <iostream>#include <stdio.h>#include <vector>#include <string>#include <unordered_map>using namespace std;/*问题: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.分析:判断两个字符串是否具有相同的结构,用同一个字符对应替换看是否能够将替换后的结果和给出的结果一致,如果得到的结果不一致,说明不等。遍历两个字符串,比如egg对add,发现e被转换成了a,g被转换成了d,建立这种映射,如果存在相同的映射,说明错误,否则,最后转换,发现相等即为正确如果两个字符串都为空,或相等,是同结构的输入:egg addfoo barpaper titleab aa输出:truefalsetruefalse关键:1 顺利被坑,没有考虑到ab ,aa这种我只用前面映射后面,会遗漏两个不同的字符指向同一个字符的情况,因此不仅要建立str1到str2的映射,也需要建立str2到str1的映射。可以把str2建立到str1的映射建立单独拿出来,不要和str1到str2的映射建立放在同一个for循环下面就可以避免: paper title会被认为是错误的同构2 a能映射到b,b也能映射到a,才叫同构*/class Solution {public:	bool isIsomorphicHelper(string& s , string& t)	{        if(s.empty() && t.empty())		{			return true;		}		else if(s.empty() || t.empty())		{			return false;		}		if(s.length() != t.length())		{			return false;		}		if(s == t)		{			return true;		}		int lenS = s.length();		int lenT = t.length();		unordered_map<char , char> visited;		for(int i = 0 ; i < lenS ; i++)		{			//找到一种新的映射,加入			if(visited.find(s.at(i)) == visited.end())			{				visited[s.at(i)] = t.at(i);			}			//该映射已经存在过,需要判断是否相等			else			{				//存入的映射不对				if(visited[s.at(i)] != t.at(i))				{					return false;				}			}		}		return true;	}    bool isIsomorphic(string s, string t) {		return isIsomorphicHelper(s,t) && isIsomorphicHelper(t,s);    }};void print(vector<int>& result){	if(result.empty())	{		cout << "no result" << endl;		return;	}	int size = result.size();	for(int i = 0 ; i < size ; i++)	{		cout << result.at(i) << " " ;	}	cout << endl;}void process(){	 Solution solution;	 string str1;	 string str2;	 while(cin >> str1 >> str2 )	 {		 bool result = solution.isIsomorphic(str1 , str2);		 cout << result << endl;	 }}int main(int argc , char* argv[]){	process();	getchar();	return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表