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

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;
	}
}


阅读更多
文章标签: java leetcode
个人分类: 算法/oj
上一篇LeetCode Count Primes
下一篇LeetCode Reverse Linked List
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭