leetcode - Isomorphic Strings

本文探讨了LeetCode上的同构字符串问题,并提供了一种利用哈希表进行判断的解决方案。通过对输入字符串s和t的遍历,确保两者间字符的一一对应关系,即s中的字符映射到t中唯一确定的字符。

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.

 1 class Solution {
 2 public:
 3     bool isIsomorphic(string s, string t) {
 4         int sHashtable[256]={0};
 5         int tHashtable[256]={0};
 6         int len = s.size();
 7         for(int i=0; i<len; i++){
 8             if(sHashtable[s[i]]==0){
 9                 if(tHashtable[t[i]]==0){
10                     sHashtable[s[i]]=t[i];
11                     tHashtable[t[i]]=s[i];
12                 }
13                 else return 0;
14             }
15             else
16             if(sHashtable[s[i]]!=t[i]) return 0;//same char map to different chars
17         }
18         return 1;
19     }
20 };

 

题目的标签是hashtable,一开始我想用简单的方法,以为只有24个字母,所以就把每个字母的映射存下来。但是后来发现,不仅仅有字母,还有数字,所以24维的数组肯定不行。另外不仅要保证同样的字母映射到同样的字母,还要保证不同的字母不能映射到一样的字母。

参考了别人的写法。 思路是建立256维数组(因为最多有256个ascii码?),然后建立两个hash表。开始遍历,如果string

s 中出现新字符,要确保映射t也是新的。如果s中是以前出现过的,那么就要验证其映射是否和以前一样。

(其实第二个hashtable 只是一个flag,用于验证是否出现过了)

 

fighting……

转载于:https://www.cnblogs.com/shnj/p/4494947.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值