【LeetCode】Isomorphic Strings 解题报告

来源:互联网 发布:c#图形编程 书籍 编辑:程序博客网 时间:2024/06/05 21:55

【LeetCode】Isomorphic Strings 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/isomorphic-strings/#/description

题目描述:

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.

Ways

这个题可以看出来使用hashmap,但是,注意的一点是不要用位置++的方式,这样的话只统计了这个字符出现的次数,没有统计对应的位置,导致出错。比如ababaa就会导致结果错误。因此,用到的是字符出现的位置+1的方式,保证能在hash位置处保存字符出现的次数。

public class Solution {    public boolean isIsomorphic(String s, String t) {        int[] m1 = new int[256];        int[] m2 = new int[256];        int len = s.length();        for(int i = 0; i < len; i++){            if(m1[s.charAt(i)] != m2[t.charAt(i)]){                return false;            }            m1[s.charAt(i)] = i + 1;            m2[t.charAt(i)] = i + 1;        }        return true;    }}

Date

2017 年 5 月 15 日

0 0
原创粉丝点击