关闭

LeetCode Isomorphic Strings

标签: javaleetcode
130人阅读 评论(0) 收藏 举报
分类:

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.

Solution:

分别用两个数组记录,两个字符串的字符,在前一次遇到这个字符的下标。如果所有的字符的下标相同,则返回true,否则false。

import java.util.*;

public class Solution {
	public boolean isIsomorphic(String s, String t) {

		int prePosition1[] = new int[1000];
		int prePosition2[] = new int[1000];

		Arrays.fill(prePosition1, -1);
		Arrays.fill(prePosition2, -1);

		int ch1, ch2;

		for (int i = 0; i < s.length(); i++) {
			ch1 = s.charAt(i);
			ch2 = t.charAt(i);
			if (prePosition1[ch1] == prePosition2[ch2]) {
				prePosition1[ch1] = i;
				prePosition2[ch2] = i;
			} else {
				return false;
			}

		}

		return true;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:61925次
    • 积分:3256
    • 等级:
    • 排名:第10432名
    • 原创:288篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论