246. Strobogrammatic Number
Last updated
Last updated
/**
* Time complexity : O(N)
* Space complexity : O(N)
*/
class Solution {
public boolean isStrobogrammatic(String num) {
// Note that using a String here and appending to it would be
// poor programming practice.
StringBuilder rotatedStringBuilder = new StringBuilder();
// Remember that we want to loop backwards through the string
for (int i = num.length() - 1; i >= 0; i--) {
char c = num.charAt(i);
if (c == '0' || c == '1' || c == '8') {
rotatedStringBuilder.append(c);
} else if (c == '6') {
rotatedStringBuilder.append('9');
} else if (c == '9') {
rotatedStringBuilder.append('6');
} else { // This must be an invalid digit.
return false;
}
}
String rotatedString = rotatedStringBuilder.toString();
return num.equals(rotatedString);
}
}/**
* Time complexity : O(N)
* Space complexity : O(1)
*/
class Solution {
public boolean isStrobogrammatic(String num) {
Map<Character, Character> dict = Map.of('0', '0',
'1', '1',
'6', '9',
'8', '8',
'9', '6');
int left = 0, right = num.length()-1;
while(left <= right) {
if(!dict.containsKey(num.charAt(left)) ||
!dict.get(num.charAt(left)).equals(num.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}