classSolution {
publicinttitleToNumber(String columnTitle) {
HashMap<Character, Integer> charToValue =new HashMap<>();
// Create the mapping from 'A' to 'Z'for (char ch ='A'; ch <='Z'; ch++) {
charToValue.put(ch, ch -'A'+ 1);
}
int ans = 0;
for (int i = 0; i < columnTitle.length(); i++) {
ans = ans * 26 + charToValue.get(columnTitle.charAt(i));
}
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution:
deftitleToNumber(self, columnTitle: str) -> int:
char_to_value = {chr(i + ord('A')): i +1for i in range(26)}
ans: int =0for char in columnTitle:
ans = ans *26+ char_to_value[char]
return ans
1
- 🧺 Space complexity: `O(1)`, since the HashMap size is fixed with 26 entries regardless of the input size.
classSolution {
publicinttitleToNumber(String columnTitle) {
int ans = 0;
for (int i = 0; i < columnTitle.length(); i++) {
ans = ans * 26 + (columnTitle.charAt(i) -'A'+ 1);
}
return ans;
}
}
1
2
3
4
5
6
classSolution:
deftitleToNumber(self, columnTitle: str) -> int:
ans: int =0for char in columnTitle:
ans = ans *26+ (ord(char) - ord('A') +1)
return ans