leetcode_205题——Isomorphic Strings(用的map)

Isomorphic Strings

  Total Accepted: 5891 Total Submissions: 24698My Submissions

 

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.

 

Hide Tags
  Hash Table
Have you met this question in a real interview? 
Yes
 
       这道题需要对于字符串s和t,s中作为键,t中作为相对应的值,有两点,.s中不同的键对应的值不同,相同的键对应的值需要相同  
 
#include<iostream>

#include<string>

#include <map>

#include <utility>

using namespace std;



bool isIsomorphic(string s, string t) {

	map<char,char> temp_map;

	int len=s.size();

	temp_map.insert(make_pair(s[0],t[0]));

	for(int i=1;i<len;i++)

	{

		int a=s[i];

		int b=t[i];

		if(temp_map.count(s[i])==1)

		{

			if(temp_map[s[i]]!=t[i])

				return false;

		}

		else

		{

			for(map<char,char>::iterator i=temp_map.begin();i!=temp_map.end();i++)

			{

				if(i->second==b)

					return false;

			}

			temp_map.insert(make_pair(s[i],t[i]));

		}

	}

	return true;

}

int main()

{

	string str1="ab";

	string str2="ca";

	cout<<isIsomorphic(str1,str2)<<endl;

}

  

你可能感兴趣的:(LeetCode)