Created
November 6, 2022 19:31
-
-
Save mustafa-qamaruddin/f7555674f480c9ff511169c45443e7d2 to your computer and use it in GitHub Desktop.
[LeetCode] 2451. Odd String Difference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
private int[] calcDiff(char[] chars) { | |
int[] diffs = new int[chars.length-1]; | |
for(int i = 0; i < chars.length - 1; i++) { | |
diffs[i] = chars[i+1] - chars[i]; | |
} | |
return diffs; | |
} | |
private boolean areArraysEq(int[] left, int[] right) { | |
if (left.length != right.length) return false; | |
for (int i = 0; i < left.length; i++) { | |
if (left[i] != right[i]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
// return index of odd: 0, 1, or 2, returns -1 otherwise | |
private int vote(int[] prevDiff, int[] midDiff, int[] currDiff) { | |
if (areArraysEq(prevDiff, midDiff) && areArraysEq(midDiff, currDiff)) { | |
return -1; | |
} | |
if (areArraysEq(midDiff, currDiff)) { | |
return 0; | |
} | |
if (areArraysEq(prevDiff, currDiff)) { | |
return 1; | |
} | |
if (areArraysEq(prevDiff, midDiff)) { | |
return 2; | |
} | |
return -1; | |
} | |
public String oddString(String[] words) { | |
for(int i = 0; i < words.length - 2; i++) { | |
int[] prevDiff = calcDiff(words[i].toCharArray()); | |
int[] midDiff = calcDiff(words[i + 1].toCharArray()); | |
int[] currDiff = calcDiff(words[i + 2].toCharArray()); | |
int voteIdx = vote(prevDiff, midDiff, currDiff); | |
if (voteIdx != -1) { | |
return words[voteIdx]; | |
} | |
} | |
return ""; | |
} | |
} | |
class Scratch { | |
public static void main(String[] args) { | |
String[][] tcs = new String[3][]; | |
tcs[0] = new String[]{"adc","wzy","abc"}; | |
tcs[1] = new String[]{"aaa","bob","ccc","ddd"}; | |
tcs[2] = new String[]{"mll","edd","jii","tss","fee","dcc","nmm","abb","utt","zyy","xww","tss","wvv","xww","utt"}; | |
for (int i = 0; i < tcs.length; i++) { | |
var sol = new Solution().oddString(tcs[i]); | |
System.out.println(sol); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment