• Java [Leetcode 205]Isomorphic Strings


    题目描述:

    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.

    解题思路:

    用数组做映射。注意每次字典映射的时候赋值为i+1,这是为了防止跟第一次映射时候的赋值混淆。(因为数组的初始化赋值为0,若每次赋值为i,那么第一次赋值的时候也为0,这样就混淆了)。

    代码如下:

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

      

  • 相关阅读:
    2017洛谷7月月赛总结
    poj3169 Layout
    poj3613Cow Relays
    洛谷P1418 选点问题
    poj3311Hie with the Pie
    poj1734Sightseeing trip
    poj3728The merchant
    洛谷P2420 让我们异或吧
    struts2.1笔记02:servlet简介
    struts2.1笔记01:MVC框架思想浅层理解
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5183907.html
Copyright © 2020-2023  润新知