1.문제
The value of an alphanumeric string can be defined as:
- The numeric representation of the string in base 10, if it comprises of digits only.
- The length of the string, otherwise.
Given an array strs of alphanumeric strings, return the maximum value of any string in strs.
문자와 숫자가 섞여있는 단어들로 이루어진 배열이 주어질 때 숫자로만 이루어진 단어라면 그대로 10진수로 바꾸었을 때 수를, 그런 경우가 아니라면 문자의 길이를 value 값으로 한다.
이럴 때 가장 큰 value 값을 리턴하는 문제이다.
Example 1
Input: strs = ["alic3","bob","3","4","00000"]
Output: 5
Explanation:
- "alic3" consists of both letters and digits, so its value is its length, i.e. 5.
- "bob" consists only of letters, so its value is also its length, i.e. 3.
- "3" consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4" also consists only of digits, so its value is 4.
- "00000" consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3".
Example 2
Input: strs = ["1","01","001","0001"]
Output: 1
Explanation:
Each string in the array has value 1. Hence, we return 1.
Constraints:
- 1 <= strs.length <= 100
- 1 <= strs[i].length <= 9
- strs[i] consists of only lowercase English letters and digits.
2.풀이
- 각 단어들을 Number를 이용해서 정수로 바꾼다.
- 만약 알파벳이 섞여있는 단어라면 NaN이 리턴되므로 그것을 기준으로 정수 판별을 한다.
- 정수가 아니라면 단어의 길이, 정수라면 그 정수값을 가지고 최댓값을 저장한다.
/**
* @param {string[]} strs
* @return {number}
*/
const maximumValue = function (strs) {
let maximum = 0;
for (let i = 0; i < strs.length; i++) {
if (isNaN(Number(strs[i]))) {
// 숫자가 아닌 단어이면 true
maximum = Math.max(maximum, strs[i].length); // 단어이면 단어의 길이와 최댓값을 비교
} else {
maximum = Math.max(maximum, parseInt(strs[i])); // 숫자이면 숫자와 최댓값을 비교
}
}
return maximum;
};
3.결과
