LeetCode_Isomorphic Strings

一.题目

Isomorphic Strings

   Total Accepted: 8671  Total Submissions: 36190 My Submissions

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.

Show Tags
Have you met this question in a real interview?  
Yes
 
No

Discuss
















二.解题技巧

    这道题主要是建立两个字符串中不同字符的对应关系,由于ASCII编码的字符只有256个,而且string中是不保存null字符的,因此,可以建立两个大小为256的字符数组来保存两个string中每一个字符在另外一个string中的对应的关系,然后遍历string中的每一个字符,如果相同位置的字符是互相对应的话,就处理下一个字符,如果不是互相对应的话,就在说明这两个string不是同等结构的。
    也可以通过两个map来实现,但是map的查找过程时间复杂度为O(lgn),但是上面对于string中的每一个字符串都需要查找,因此,使用map的话,时间复杂度太高了。也可以使用hash表来做,也就是使用unordered_map来实现,但是由于ASCII编码的字符的个数是固定的而且个数比较少,使用数组完全可以很好地实现。


三.实现代码

#include <string>
#include <vector>

using std::string;
using std::vector;

class Solution
{
public:
    bool isIsomorphic(string s, string t)
    {
        vector<unsigned char> First(256, 0);
        vector<unsigned char> Second(256, 0);

        const int SIZE = s.size();

        for (int Index = 0; Index < SIZE; Index++)
        {
            unsigned char ElementOfFirst = s[Index];
            unsigned char ElementOfSecond = t[Index];

            unsigned char& First2Second = First[ElementOfSecond];
            unsigned char& Second2First = Second[ElementOfFirst];

            if (First2Second != 0 && Second2First != 0)
            {

                if (First2Second != ElementOfFirst)
                {
                    return false;
                }


                if (Second2First != ElementOfSecond)
                {
                    return false;
                }
                continue;
            }

            if (First2Second == 0 && Second2First == 0)
            {
                First2Second = ElementOfFirst;
                Second2First = ElementOfSecond;

                continue;
            }

            return false;
        }

        return true;
    }
};




四.体会

    这道题就是寻找一个好的数据结构来保存两个string之间的字符的对应关系,根据这道题的假设,选择数组是一个比较的解决方案。



版权所有,欢迎转载,转载请注明出处,谢谢微笑





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值