zoukankan      html  css  js  c++  java
  • Leetcode 205. Isomorphic Strings

    205. Isomorphic Strings

    Total Accepted: 62899 Total Submissions: 206548 Difficulty: Easy

    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.

    思路:判断2个字符串是否同构。其实就是映射的问题,如果s和t的字符是一一映射(双射)的关系,就可以说s和t是同构的。

    代码:

    方法一:将s和t中的字符分别一一映射于整数集合,再对比映射以后的s和t是否相等。

     1 class Solution {
     2 public:
     3     string trans(string s){
     4         int i,m[256]={0};
     5         for(i=0;i<s.size();i++){
     6             if(!m[s[i]]){
     7                 m[s[i]]=i+1;
     8             }
     9             s[i]=m[s[i]];
    10         }
    11         return s;
    12     }
    13     bool isIsomorphic(string s, string t) {
    14         if(trans(s)==trans(t))
    15             return true;
    16         return false;
    17     }
    18 };

    方法二:
    看是否能将s转换为t:

     1 class Solution {
     2 public:
     3     bool isIsomorphic(string s, string t) {
     4         char m['z'+1]={0};
     5         bool b['z'+1]={false};
     6         int i;
     7         for(i=0;i<s.size();i++){
     8             if(!m[s[i]]&&!b[t[i]]){
     9                 m[s[i]]=t[i];
    10                 b[t[i]]=true;
    11             }
    12             if(m[s[i]]==t[i]){
    13                 continue;
    14             }
    15             return false;
    16         }
    17         return true;
    18     }
    19 };

    方法三:看当前字符最近一次出现的位置是否相等。

     1 class Solution {
     2 public:
     3     bool isIsomorphic(string s, string t) {
     4         int m1[256] = {0}, m2[256] = {0}, n = s.size();
     5         for (int i = 0; i < n; ++i) {
     6             if (m1[s[i]] != m2[t[i]]) return false;
     7             //因为初始值为0,所以要i+1
     8             m1[s[i]] = i + 1; //m1记录s[i]在s中最近一次出现的位置
     9             m2[t[i]] = i + 1;
    10         }
    11         return true;
    12     }
    13 };
  • 相关阅读:
    haproxy 安装与配置
    Rancher使用入门
    Docker中配置国内镜像
    【转】【VC】VC程序运行时间测试函数
    【转】PNG图像文件格式
    【转】BMP图像文件格式
    【转】OPenGL MFC绘图
    OPenGL 库文件的添加
    【转】MFC WM_CTLCOLOR 消息
    【转】C#获取电脑客户端IP地址及当前用户名
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5632280.html
Copyright © 2011-2022 走看看