码迷,mamicode.com
首页 > 其他好文 > 详细

Lettcode_205_Isomorphic Strings

时间:2015-06-17 11:35:30      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   java   string   

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/46530865



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.


思路:

(1)题意为给定两个长度相同的字符串,判断这两个字符串中相同字符位置上是否相对应。

(2)要判断相同字符的位置是否相对应,需要记录所有字符出现的位置。首先,创建两个不同的Map分别来保存两个字符串相关信息,其中key为字符串中的字符,value为该字符在字符串中的下标(下标以字符串形式保存),例如:egg和add的保存形式分别为{e={"1"},g={"23"}}和{a={"1"},d={"23"}}。其次,只需要遍历字符数组中的每一个字符,如果Map对应的key中不包含当前遍历的字符,则将该字符及其位置存入Map中,否则,则从Map中取出当前字符对应的value,将当前字符位置追加到value上。最后,遍历完字符数组后,需要判断两个Map所对应value大小是否相同,不相同则返回false,否则,分别将两个Map中value值依次放入两个新的StringBuffer中,如果最后得到的字符串内容相同,则返回true,否则返回false。例如:egg和add最后得到的字符串都为“123”,而pick和good对应的Map为{p={"1"},i={"2"},c={"3"},k={"4"}}和{g={"1"},o={"23"},d={"4"}},显然两个Map对应value大小不同,所以返回false。

(3)详情将下方代码。希望本文对你有所帮助。


算法代码实现如下:

package leetcode;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 
 * @author liqq
 *
 */
public class Isomorphic_Strings {
	public static  boolean isIsomorphic(String s, String t) {

		char[] ch1 = s.toCharArray();
		char[] ch2 = t.toCharArray();
		int len = ch1.length;
		
		Map<Character, StringBuffer> _map1 = new LinkedHashMap<Character, StringBuffer>();
		Map<Character, StringBuffer> _map2 = new LinkedHashMap<Character, StringBuffer>();
		
		for (int i = 0; i < len; i++) {
			if(_map1.get(ch1[i])==null){
				_map1.put(ch1[i], new StringBuffer());
				_map1.get(ch1[i]).append(i);
			}else{
				_map1.get(ch1[i]).append(i);
			}
			
			if(_map2.get(ch2[i])==null){
				_map2.put(ch2[i], new StringBuffer());
				_map2.get(ch2[i]).append(i);
			}else{
				_map2.get(ch2[i]).append(i);
			}
			
			if(_map1.values().size()!=_map2.values().size()){
				return false;
			}
		}
		
		StringBuffer b1 = new StringBuffer();
		StringBuffer b2 = new StringBuffer();
		for (Iterator<StringBuffer> iterator1 = _map1.values().iterator(),iterator2 = _map2.values().iterator(); 
				iterator1.hasNext()&&iterator2.hasNext();) {
			b1.append(iterator1.next());
			b2.append(iterator2.next());
		}
		
		return b1.toString().equals(b2.toString());
	}
}


Lettcode_205_Isomorphic Strings

标签:leetcode   算法   java   string   

原文地址:http://blog.csdn.net/pistolove/article/details/46530865

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!