LeetCode 226Isomorphic Strings

来源:互联网 发布:dnf一上线就网络中断 编辑:程序博客网 时间:2024/06/05 04:26

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.

题目要求判断一个字符串中是否可以有另一个字符串中得数字替换而来.

其实就是找映射关系,而且这种映射关系是一一对应的。

C++:

class Solution {public: bool isIsomorphic(string s, string t) {    int len1=s.length();    int len2=t.length();    if(len1!=len2)        return false;    vector<int>v(200,-1); //存放映射关系    bool vis[200]={0};   //检验映射关系的唯一性    int i=0;    int j=0;    string temp=t;    while(j<len1)    {        if(v[temp[j]]!=-1)            temp[j]=v[temp[j]];        else        {            if(vis[s[j]]==0)            {                v[temp[j]]=s[j];                temp[j]=s[j];                vis[s[j]]=1;            }            else                break;              }        j++;    }       if(temp==s && j==len1)        return true;    return false;      }};


0 0
原创粉丝点击