LeetCode day7

205. 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.

Example 1:
Input: s = “egg”, t = “add”
Output: true

Example 2:
Input: s = “foo”, t = “bar”
Output: false

Example 3:
Input: s = “paper”, t = “title”
Output: true

分析

一开始想着发现一共字符串相同的字符的位置,然后试图在另外一个字符串里面对应位置确定是不是也有相同字符串,但位置多变,而且字符和字符之间没有固定的对应关系,就陷入了死胡同。看了大神的评论,恍然大悟,直呼内行。
大神的思路是用两个大小为256的数组,初始化全为0,用嵌套数组的方法,同时遍历两个字符串,若遍历完两个256大数组的比较一直相等,则两个字符串为同构字符串,输出true,否则输出false。其中妙就秒在不用考虑字符之间的映射关系,即大小为256的数组的索引由字符的ASCII构成,只需要比较m[256]与n[256]对应的数值即可。

代码

#include<iostream>
#include<string>
using namespace std;

class Solution {
public:
	bool isIsomorphic(string s, string t) {
		int m[256] = { 0 };
		int n[256] = { 0 };

		for (int i = 0; i < s.size(); i++) {
			// 首次都为0,其后若字符串结构不同,+1的次数不同,必然导致
		    // 以下判断成立,则输出false
			if (m[s[i]] != n[t[i]]) {
				return false;
			}
			m[s[i]] += 1;
			n[t[i]] += 1;
		}
		return true;
	}
};

int main() {
	Solution solution;

	string s = "paper";
	string t = "title";

	solution.isIsomorphic(s, t) ? cout << s <<" is isomorphic to " <<t<< endl : cout << s << " is not isomorphic to " << t << endl;
	return 0;
}

复杂度分析

时间复杂度空间复杂度
O(n)O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值