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.

      Note:
      You may assume both s and t have the same length.

      这题难度不大。

      第一个程序(28ms):

     1 bool isIsomorphic(string s, string t) {
     2     unordered_map<char, char> hashMap;
     3     int sz = s.size();
     4     for(int i = 0; i < sz; i++)
     5     {
     6         if(hashMap.find(s[i]) != hashMap.end())
     7         {
     8             if(hashMap[s[i]] != t[i])
     9                 return false;
    10         }
    11         else
    12         {
    13             unordered_map<char, char>::iterator itr = hashMap.begin();
    14             for(; itr != hashMap.end(); itr++)
    15                 if(itr->second == t[i])
    16                     return false;
    17 
    18             hashMap[s[i]] = t[i];
    19         }
    20             
    21     }
    22     
    23     return true;
    24 }

      第二个程序(24ms):

     1 bool isIsomorphic(string s, string t) {
     2     unordered_map<char, char> hashMap;
     3     unordered_map<char, char> rHashMap;
     4     int sz = s.size();
     5     for(int i = 0; i < sz; i++)
     6     {
     7         if(hashMap.find(s[i]) != hashMap.end())
     8         {
     9             if(hashMap[s[i]] != t[i])
    10                 return false;
    11         }
    12         else
    13         {
    14             if(rHashMap.find(t[i]) != rHashMap.end())
    15                 return false;
    16             
    17             hashMap[s[i]] = t[i];
    18             rHashMap[t[i]] = s[i];
    19         }
    20     }
    21     
    22     return true;
    23 }

      看了网上别人的做法(少掉了哈希表查找的时间损耗),只需8ms

     1 bool isIsomorphic(string s, string t) {
     2     char map_s[128] = { 0 };
     3     char map_t[128] = { 0 };
     4     int len = s.size();
     5     for (int i = 0; i < len; ++i)
     6     {
     7         if (map_s[s[i]]!=map_t[t[i]]) return false;
     8         map_s[s[i]] = i+1;
     9         map_t[t[i]] = i+1;
    10     }
    11     
    12     return true;  
    13 }
  • 相关阅读:
    《代码整洁之道》读书笔记六
    第九周总结
    《构建之法》读后感(五)
    学习进度条-第十二周
    3. 统计数字
    《构建之法》读后感(四)
    学习进度条-第十一周
    4. 丑数 II
    《构建之法》读后感(三)
    学习进度条-第十周
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4592333.html
Copyright © 2011-2022 走看看