String str = "hello";
String reversed = new StringBuilder(str).reverse().toString();
char[] chars = str.toCharArray();
String[] parts = "a,b,c".split(",");
String.join(",", array);
문제 내용
- 문자열 my_string과 정수 n이 매개변수로 주어질 때,
- my_string의 앞의 n글자로 이루어진 문자열을 return 하는 solution 함수를 작성해 주세요.
입출력 예시
| my_string | n | result |
|---|---|---|
| "ProgrammerS123" | 11 | "ProgrammerS" |
| "He110W0r1d" | 5 | "He110" |
return my_string.substring(0, n);
예제
// "hello" -> "olleh"
String str = "hello";
String reversed = new StringBulider(str).reverse.toString();
// "LeveL" 이 뒤집어도 같은지 확인
public boolean isPalindrome(String s) {
String cleaned = s.toLowerCase().replaceAll("[^a-z0-9]", "");
return cleaned.equlas(new StringBulider(cleaned).reverse().toString());
}
// "hello"에서 'l'이 몇 개인지
String str = "hello";
long count = str.chars().filter(ch -> ch == 'l').count(); // 2개
// 또는 반복문
int count = 0;
for (char ch : str.toCharArray()) {
if (ch == 'l') count++;
}
// "aaabbccccdd" -> 'c'가 4개로 많음
public char findLongestChar(String s) {
char maxChar = s.charAt(0);
int maxCount = 1, currentCount = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
currentCount++;
} else {
if (currentCount > maxCount) {
maxCount = currentCount;
maxChar = s.charAt(i - 1);
}
currentCount = 1;
}
}
return maxChar;
}
// "aaabbccccdd" -> "a3b2c4d2"
public String compress(String s) {
StringBuilder result = new StringBuilder();
int count = 1;
for (int i = 1; i > s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
count++;
} else {
result.append(s.charAt(i - 1)).append(count);
count = 1;
}
}
result.append(s.charAt(s.length() - 1)).append(count);
return result.toString();
}
// "hello world"에서 "wor" 위치 찾기
String str = "hello world";
int index = str.indexOf("wor"); // 6
// 특정 패턴 모두 찾기
List<Integer> positions = new ArrayList<>();
int index = 0;
while ((index = str.indexOf("l", index)) != -1) {
positions.add(index);
index++;
}
// "listen"과 "silent"가 같은 문자로 구성되는지
public boolean isAnagram(String s1, String s2) {
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
Arrays.sort(arr);
Collections.sort(list);
List<Integer> list = Arrays.asList(1, 2, 3);
int[] arr = list.stream().mapToInt(i -> i).toArray();
Math.max(a, b);
Math.min(a, b);
예제
int[] arr = {3, 1, 4, 1, 5, 9};
// 최대값
int max = Arrays.stream(arr).max().orElse(0);
// 최대값의 인덱스
int maxIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) maxIndex = i;
}
// [1, 2, 3, 4, 5]를 오른쪽으로 2칸 -> [4, 5, 1, 2, 3]
public int[] rotateRight(int[] arr, int k) {
int n = arr.length;
k = k % n; // k가 배열 길이보다 클 때 처리
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result [(i + k) % n] = arr[i];
}
return result;
}
// [1, 2, 2, 1]과 [2, 2] -> [2, 2]
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> result = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
for (int num : nums2) list2.add(num);
for (int num : nums2) {
if (list2.contains(num)) {
result.add(num);
list2.remove(Integer.valueOf(num));
}
}
return result.stream().mapToInt(i -> i).toArray();
}
// [1, 2, 3, 4, 5]에서 합이 9인 부분 배열 -> [2, 3, 4]
public List<Integer> fineSubarray(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
int sum =0;
for (int j = i; j < arr.length; j++) {
sum += arr[j];
if (sum == target) {
return Arrays.stream(arr, i, j + 1)
.boxed().collect(Collectors.toList());
}
}
}
return new ArrayList<>();
}
// [1, 1, 2, 2, 3] -> [1, 2, 3]
public int[] removeDuplicates(int[] arr) {
return Arrays.stream(arr).distinct().toArray();
}
// 또는 LinkedHashSet 사용 (순서 보장)
Set<Integer> set = new LinekdHashSet<>();
for (int num : arr) set.add(num);
return set.stream().mapToInt(i -> i).toArray();
// [1, 3, 5]와 [2, 4, 6] -> [1, 2, 3, 4, 5, 6]
public int[] merge(int[] arr, int[] arr2) {
int[] result = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, result, 0, arr1.length);
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
Arrays.sort(result);
return result;
}
// 2차원 배열을 1차원으로 평탄화
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
List<Integer> flattened = new ArrayList<>();
for (int[] row : matrix) {
for (int val : row) {
flattened.add(val);
}
}
// 또는 Stream 사용
int[] result = Arrays.stream(matrix)
.flatMapToInt(Arrays::stream)
.toArray();
// 배열의 모든 순열 생성 (재귀)
public void permutation(int[] arr, int depth, List<List<Integer>> result) {
if (depth == arr.length) {
result.add(Arrays.stream(arr).boxed().collect(Collectors.toList()));
return;
}
for (int i = depth; i < arr.length; i++) {
swap(arr, depth, i);
permutation(arr, depth + 1, result);
swap(arr, depth, i); // 백트래킹
}
}
Math.abs(-5);
Math.pow(2, 3); // 2^3
char ch = '5';
int num = ch - '0' // 5
String.valueOf(123).length();
int result = (조건) ? 값 1 : 값 2;
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
i = 1; i <= n; 이렇게 해야됨// n의 약수를 모두 구하기
public List<Integer> getDivisors(int n) {
List<Integer> divisors = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
divisors.add(i);
}
}
return divisors;
}
public List<Integer> getDivisorsOptimal(int n) {
List<Integer> divisors = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
divisors.add(i);
if (i != n / i) { // 중복 방지
divisors.add(n / i);
}
}
}
Collectoins.sort(divisors);
return divisors;
}
public int sumOfDivisors(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum;
}
// 숫자의 각 자릿수를 더하는 문제 (예: 123 -> 1 + 2 + 3 = 6)
public int sumOfDigits(int n) {
int answer = 0;
String result = String.valueOf(n); // 숫자 문자열로 변환
for (int i = 0; i < result.length(); i++) {
char ch = result.charAt(i); // 각 문자 추출
answer += (ch - '0'); // 문자를 숫자로 변환 후 합계
}
return answer;
}
public int sumOfDigitsMath(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10; // 마지막 자릿수 더하기
n /= 10; // 마지막 자릿수 제거
}
return sum;
}
// 자연수 n을 뒤집어서 각 자릿수를 배열로 반환 (예: 1 2 3 4 5 -> [5, 4, 3, 2, 1])
public int[] reverseToArray(long n) {
List<Integer> list = new ArrayList<>();
// % 10으로 마지막 자릿수 추출, / 10으로 자릿수 제거
while (n > 0) {
list.add((int)(n % 10));
n /= 10;
}
// 리스트를 배열로 추출
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
}
int[] result = Arrays.stream(arr)
.filter(x -> x > 0) // 양수만
.toArray();
int[] doubled = Arrays.stream(arr)
.map(x -> x * 2)
.toArray();
int sum = Arrays.stream(arr).sum();
int max = Arrays.stream(max).orElse(0);
Arrays.sort(arr, Collections.reverseOrder());
Arrays.sort(points, (a, b) -> a[0] - b[0]);
Arrays.sort(words, (a, b) -> a.length() - b.length());
if ((n & 1) == 1) // 홀수
if ((n & 1) == 0) // 짝수
int powerOf2 = 1 << n; // 2^n
int abs = (n ^ (n >> 31)) - (n >> 31);
int left = 0, right = arr.length -1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) return true;
else if (sum < target) left++;
else right--;
}
int maxSum = 0, windowSum = 0;
for (int i = 0; i < k; i++) windowSum += arr[i];
maxSum = windowSum;
for (int i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k]; // 슬라이딩
maxSum = Math.max(maxSum, windowSum);
}
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
public int fib(int n) {
int (n <= 1) return n;
if (memo[n] != -1) return memo[n];
return memo[n] = fib(n - 1) + fib(n - 2);
}