코딩테스트 풀이/JAVA
[LeetCode/Easy] 205. Isomorphic Strings
무지맘
2023. 1. 23. 15:13
1. Input
1) String s
2) String t
2. Output
1) s와 t의 구조가 같으면 true, 다르면 false를 반환
- 구조가 같다는 것은, s의 알파벳들이 t에 있는 것으로 대체됐을 때 같은 단어가 된다는 것을 의미한다.
3. Constraint
1) 1 <= s.length <= 5 * 10^4
2) t.length == s.length
3) s와 t에는 유효한 ascii 문자들로 이루어져 있다.
4. Example
Input: s = "egg", t = "add" -> Output: true
Input: s = "foo", t = "bar" -> Output: false
5. Code
1) 첫 코드(2023/01/23)
import java.util.*;
int num = 0;
String numS = "";
HashMap<Character, Integer> ss = new HashMap<Character, Integer>();
for(int i=0 ; i<s.length() ; i++){
if(!ss.containsKey(s.charAt(i))){
ss.put(s.charAt(i), num);
numS += num++ + ",";
} else{
numS += ss.get(s.charAt(i)) + ",";
}
}
num = 0;
String numT = "";
HashMap<Character, Integer> tt = new HashMap<Character, Integer>();
for(int i=0 ; i<t.length() ; i++){
if(!tt.containsKey(t.charAt(i))){
tt.put(t.charAt(i), num);
numT += num++ + ",";
} else{
numT += tt.get(t.charAt(i)) + ",";
}
}
return numS.equals(numT);
- 하위 5퍼의 성능을 갖고 있는 코드
2) 수정해본 코드(2023/01/23)
import java.util.*;
int ns = 0, nt = 0;
boolean answer = true;
HashMap<Character, Integer> ss = new HashMap<Character, Integer>();
HashMap<Character, Integer> tt = new HashMap<Character, Integer>();
for(int i=0 ; i<s.length() ; i++){
if(!ss.containsKey(s.charAt(i))) ss.put(s.charAt(i), ns++);
if(!tt.containsKey(t.charAt(i))) tt.put(t.charAt(i), nt++);
if(ss.get(s.charAt(i))!=tt.get(t.charAt(i))){
answer = false; break;
}
}
return answer;
- 실행시간은 상위 40%, 메모리 사용은 상위 7% 코드로 신분 상승했다.