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 };
  • 相关阅读:
    VUE body 背景色
    BUTTON莫名出现黄色边框 :focus
    VUE SVG
    【噶】字符串-680. 验证回文字符串 Ⅱ
    【噶】数组-两数之和(哈希表)
    【噶】数组-面试题 16.11. 跳水板
    【噶】字符串-58. 最后一个单词的长度
    Ajax_Jason 使用小Demo
    tomcat_部署项目以及相关问题
    js 表单的选择与反选简单操作
  • 原文地址:https://www.cnblogs.com/LUO77/p/5050356.html
Copyright © 2011-2022 走看看