My Java Solution : Tracing the next index of same character


  • 0
    A
    public class Solution {
        Map<Character,Integer> map = new HashMap<Character, Integer>();
        public boolean isIsomorphic(String s, String t) {
            if(s.length() != t.length()){
                return false;
            }
            int i;
            int arr[] = new int[s.length()];
            for(i=s.length()-1; i>=0; i-- ){
                if(map.containsKey(s.charAt(i)) ){
                    arr[i] = map.get(s.charAt(i));
                    map.put(s.charAt(i),i);
                }
                else{
                    arr[i] = i;
                    map.put(s.charAt(i),i);
                }
            }
            
            map.clear();
            for(i=t.length()-1; i>=0; i-- ){
                if(map.containsKey(t.charAt(i)) ){
                    
                    if(arr[i] != map.get(t.charAt(i))){
                        return false;
                    }
                    map.put(t.charAt(i),i);
                }
                else{
                    if(arr[i] != i){
                        return false;
                    }
                    map.put(t.charAt(i),i);
                }
            }
            return true;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.