zoukankan      html  css  js  c++  java
  • leetcode Isomorphic Strings

    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.

    没做出来。

    没有非常清楚的理解题目的意思,题目是说,两个字符串同构。我却认为是只要字符串s中哪些字符串一样,t中相同位置的字符串也要一样。

    事实上约束更多,讲的是一种映射,就如同egg,e与a映射,g与d映射,那么字符串s中如果再出现e,字符串t中就必须是a。

    所以,构建一个map,用上次见过的方法就行了。if(map.find(s[i])==map.end())****else****

    不过需要有两次检查,检查s->t的映射t是否满足,还有t->s的映射s是否满足。

     1 class Solution {
     2 public:
     3     bool isIsomorphic(string s, string t) {
     4         map<char,char> model;
     5         int slength=s.length(),tlength=t.length();
     6         if(slength!=tlength) return false;
     7         for(int i=0;i<slength;i++){
     8             if(model.find(s[i])==model.end()) model[s[i]]=t[i];
     9             else if(model[s[i]]!=t[i]) return false;
    10         }
    11         model.clear();
    12         for(int i=0;i<slength;i++){
    13             if(model.find(t[i])==model.end()) model[t[i]]=s[i];
    14             else if(model[t[i]]!=s[i]) return false;
    15         }
    16         return true;
    17 
    18         
    19     }
    20 };
  • 相关阅读:
    Linux Mint---shutter截图软件
    Linux Mint---fcitx中文,日语输入法
    Linux Mint---安装docky
    Linux Mint---开启桌面三维特效
    Linux Mint---ATI显卡驱动安装篇
    Linux Mint---更新软件源
    Spring Cloud 微服务服务间调用session共享问题
    Jooq批量插入 batch
    idea安装SonarLint语法检测插件
    JVM到底是什么?
  • 原文地址:https://www.cnblogs.com/LUO77/p/5050356.html
Copyright © 2011-2022 走看看