class Solution {
public boolean buddyStrings(String s, String goal) {
boolean hasSame = false;
int[] chars = new int[26];
if (s.length() != goal.length()) {
return false;
}
int pos1 = -1;
int pos2 = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
if (pos1 != -1 && pos2 != -1) {
return false;
} else if (pos1 == -1) {
pos1 = i;
} else {
pos2 = i;
}
}
chars[s.charAt(i) - 'a']++;
if (chars[s.charAt(i) - 'a'] >= 2) {
hasSame = true;
}
}
if (pos1 == -1 && pos2 == -1) {
return hasSame;
}
if (pos2 == -1) {
return false;
}
return (s.charAt(pos1) == goal.charAt(pos2)) && (s.charAt(pos2) == goal.charAt(pos1));
}
}
Runtime: 3 ms, faster than 48.93% of Java online submissions for Buddy Strings.
Memory Usage: 38.7 MB, less than 95.53% of Java online submissions for Buddy Strings.
"aa" 이런 케이스들 처음에 풀때 절대 통과 못하는데
인터뷰가 조금 걱정되네유ㅠㅠ
돌려보기전까지 죽어도 생각 안나는 에지케이즈들~~
class Solution {
public int[][] diagonalSort(int[][] mat) {
// Store the matrix dimensions
int m = mat.length;
int n = mat[0].length;
// Data structure to store the diagonals.
Map<Integer, Queue<Integer>> diagonals = new HashMap<>();
// Insert values into the HashMap.
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
//row - col: diagonals
diagonals.putIfAbsent(row - col, new PriorityQueue<>());
diagonals.get(row - col).add(mat[row][col]);
}
}
// Take values back out of the HashMap.
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
mat[row][col] = diagonals.get(row - col).remove();
}
}
return mat;
}
}
Runtime: 10 ms, faster than 26.77% of Java online submissions for Sort the Matrix Diagonally.
Memory Usage: 39.8 MB, less than 77.97% of Java online submissions for Sort the Matrix Diagonally.
diagonal 같은 애들이 다 같은 row - col이 있다는 점...^^
그거 하나하나 sort 해주고 다시 넣어주는 방식..