문제
You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s.
Example 1:
Input: s = "hello"
Output: 13
Explanation:
The ASCII values of the characters in s are: 'h' = 104, 'e' = 101, 'l' = 108, 'o' = 111. So, the score of s would be |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13.
Example 2:
Input: s = "zaz"
Output: 50
Explanation:
The ASCII values of the characters in s are: 'z' = 122, 'a' = 97. So, the score of s would be |122 - 97| + |97 - 122| = 25 + 25 = 50.
Constraints:
- 2 <= s.length <= 100
- s consists only of lowercase English letters.
분석
- 문자열 변수 s가 주어지면 s의 각 문자의 아스키코드 값에 따라 서로 인접한 문자끼리 아스키코드값의 차이를 구하여 총 차이를 더한다.
- s.length 로 순회하면서 s.charAt(i) 로 확인하기
OR s를 toCharArray() 를 통해 char 형태의 리스트로 만들어 for로 순회하기
=> 🤖 Copliot 의 추천
- 방법 1 (s.length()와 s.charAt(i)):
- 장점: 별도의 배열을 생성하지 않고 문자열의 각 문자를 직접 접근합니다.
- 성능: s.length()와 s.charAt(i)는 시간 복잡도가 $O(1)$인 메서드입니다.
- 메모리 사용량: 추가 메모리를 사용하지 않습니다.
- 방법 2 (s.toCharArray()):
- 장점: 한 번의 배열 생성으로 문자열의 각 문자를 빠르게 접근할 수 있습니다.
- 성능: s.toCharArray()는 문자열을 char 배열로 변환하는 데 $O(n)$의 시간이 소요되며, 이 후 배열 순회는 $O(n)$입니다.
- 메모리 사용량: 추가적인 배열 메모리를 사용합니다.
- 효율성 측면: 문자열의 길이가 비교적 짧고(최대 100 문자) 반복문 내에서 각 문자를 처리하는 작업이 간단한 경우, 두 방법 간의 성능 차이는 미미합니다.
- 메모리 사용량 측면: 추가 메모리를 사용하지 않는 방법 1 (s.length()와 s.charAt(i))이 조금 더 효율적일 수 있습니다.
- 코드 가독성 측면: 방법 2 (s.toCharArray())는 코드가 더 직관적일 수 있습니다.
- 방법 1 (s.length()와 s.charAt(i)):
- 결론적으로는 s.length 로 for 순회하여 s.charAt 을 쓰기로 함.
- 순회는 인접한 문자끼리 하기 때문에 i 와 i+1 번째 문자를 비교할 것이고, for 는 s.length() - 2 까지로 진행.
답안
class Solution {
public int scoreOfString(String s) {
int answer = 0;
for(int i = 0; i <= s.length()-2; i++){
int tmp = s.charAt(i) - s.charAt(i+1);
if(tmp < 0) tmp *= -1; // 양수로 만들기
answer += tmp;
}
return answer;
}
}
다른 사람의 답안
// 1번. 시간효율이 더 좋은 코드.
// 재귀함수로 만들어버렸다...
class Solution {
public int scoreOfString(String s) {
return scoreOfStringHelper(s, 0);
}
private int scoreOfStringHelper(String s, int index) {
if (index >= s.length() - 1) {
return 0;
}
int diff = Math.abs(s.charAt(index) - s.charAt(index + 1));
return diff + scoreOfStringHelper(s, index + 1);
}
}
/*
2번 코드.
내가 for 에서 양수로 값을 구하기 위해 int tmp 를 썼는데,
이걸 쓰지 않고 바로 Math의 절대값 메서드를 사용한 경우.
시간적으로는 얼마나 차이나는지도 궁금한데...
*/
class Solution {
public int scoreOfString(String s) {
int count=0;
for(int i=1;i<s.length();i++)
{
//count += Math.abs(s.charAt(i)-s.charAt(i - 1));
count += Math.abs(s.charAt(i) - s.charAt(i - 1));
}
return count;
}
}
🔗링크
'코딩테스트 > 리트코드LeetCode' 카테고리의 다른 글
[리트코드LeetCode][Easy][JAVA]1929. Concatenation of Array (1) | 2025.01.26 |
---|---|
[리트코드LeetCode][Easy][JAVA]88. Merge Sorted Array (1) | 2024.12.31 |
[리트코드LeetCode][Easy][JAVA]2769. Find the Maximum Achievable Number (1) | 2024.12.29 |
[리트코드][LeetCode][Easy][JAVA]35. Search Insert Position (2) | 2024.09.21 |
[리트코드LeetCode][Easy][JAVA]58. Length of Last Word (1) | 2024.09.21 |