• 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 }
  • 相关阅读:
    Linux 下用 Python 连接 MSSql Server 2008
    这周我加星(4)
    几个受益终身的英文缩写
    这周我加星(1)
    证据
    这周我加星(3)
    代友招人────3D 客户端程序员
    人在广州,力撑陈 Sir
    谁不会成为 Linux(ubuntu)的用户
    这周我加星(5)
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4592333.html
Copyright © 2020-2023  润新知