Leetcode-205. Isomorphic Strings

来源:互联网 发布:netstat 监听端口 编辑:程序博客网 时间:2024/05/21 16:21

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.

这个题目到时没啥好说的,可以把字符串换成对应的数字,然后比较一下即可。Your runtime beats 4.10% of java submissions.

public class Solution {    public boolean isIsomorphic(String s, String t) {        String patternS = getPattern(s);        String patternT = getPattern(t);        return patternS.equals(patternT);    }    public String getPattern(String s){        int number = 1;        StringBuffer sb = new StringBuffer("");        Map<Character,Integer> str2number = new HashMap<Character,Integer>();        for(int i = 0; i < s.length(); i ++){            if(!str2number.containsKey(s.charAt(i))){                str2number.put(s.charAt(i),number);                sb.append(number);                number ++;            }else{                sb.append(str2number.get(s.charAt(i)));            }        }        return sb.toString();    }}




0 0