본문 바로가기

카테고리 없음

TIL(2021-11-09)

16. 문자열 내 p와 y의 개수

class Solution {
    boolean solution(String s) {
        boolean answer = true;
        int count_p=0;
        int count_q=0;
        
        s = s.toLowerCase();
                        
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='p'){
                count_p += 1;
            }
            
            if(s.charAt(i)=='y') {
                count_q += 1;
            }
        }
        
        if(count_p != count_q){
            answer=false;
        }
        else{
            answer=true;
        }
        
        return answer;
    }
}

 

17. 문자열 다루기 기본

더보기

import java.util.*;

class Solution {
public boolean solution(String s) {
char tmp;
boolean answer = true;

if(s.length() != 4 && s.length() !=6)
return false;

for (int i=0 ; i<s.length() ; i++){
tmp = s.charAt(i);

if(Character.isDigit(tmp)==false){
answer=false;
}
}
return answer;
}
}

public class Main {
public static void main(String[] args) {
Solution sol = new Solution();

String s1="a234";
String s2="1234";

boolean result1=sol.solution(s1);
boolean result2=sol.solution(s2);

System.out.println(s1 +" = "+ result1);
System.out.println(s2 +" = "+ result2);
}
}

 

18. 서울에서 김서방 찾기

더보기

import java.util.Arrays;

class Solution {
public String solution(String[] seoul) {
String answer = "";

answer += "김서방은 ";
answer += Arrays.asList(seoul).indexOf("Kim");
answer += "에 있습니다.";

return answer;
}
}

 

20. 완주하지 못한 선수

아래 블로그 참고하여 Hash 함수를 볼 예정.

https://coding-grandpa.tistory.com/entry/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%99%84%EC%A3%BC%ED%95%98%EC%A7%80-%EB%AA%BB%ED%95%9C-%EC%84%A0%EC%88%98-%ED%95%B4%EC%8B%9C-Lv-1

 

더보기

//sort 후 배열 비교를 하는 방식.

import java.util.*;
class Solution {
    public String solution(String[] participant, String[] completion) {
        // 1. 두 배열을 정렬한다
        Arrays.sort(participant);
        Arrays.sort(completion);
        // 2. 두 배열이 다를 때까지 찾는다
        int i = 0;
        for(i=0;i<completion.length;i++)
            if(!participant[i].equals(completion[i]))
                break;

        // 3. 여기까지 왔다는 것은 마지막 주자가 완주하지 못했다는 의미이다.
            return participant[i];
        }
}

더보기

class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
String compare = "";
int count=0;

loopI:
for (int i = 0; i < participant.length; i++) {
compare = participant[i];

for (int j = 0; j < completion.length; j++) {
if(compare==completion[j]){
completion[j]="";
count += 1;
System.out.print("비교 대상 "+ compare + " " + completion[j] + "\n");
}
}
if (count != 1){
answer=compare;
break loopI;
}
count=0;
}
System.out.println("못나온자 : "+ answer);
return answer;
}
}


public class Main {
public static void main(String[] args) {
Solution sol = new Solution();

String[] participant1 = {"leo","kiki","eden"};
String[] completion1 = {"eden","kiki"};

String[] participant2 = {"marina", "josipa", "nikola", "vinko", "filipa"};
String[] completion2 = {"josipa", "filipa", "marina", "nikola"};

String[] participant3 = {"mislav", "stanko", "mislav", "ana"};
String[] completion3 = {"stanko", "ana", "mislav"};

String result1 = sol.solution(participant1,completion1);
String result2 = sol.solution(participant2,completion2);
String result3 = sol.solution(participant3,completion3);

System.out.println("\n결과창");
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}

더보기
import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        String compare = "";

        int count=0;

        ArrayList<String> comparelist = new ArrayList<>();

        System.out.println("출발자 리스트");
        for(int i=0;i< participant.length;i++){
            System.out.print(participant[i]+" ");
        }

        System.out.println("\n비교대상 리스트");
        for (int i=0;i<completion.length;i++) {
            comparelist.add(completion[i]);
            System.out.print(comparelist.get(i)+" ");
        }


        loopI:
        for (int i = 0; i < participant.length; i++) {
            compare = participant[i];
            System.out.println("\n\n비교 대상 "+(i+1)+"번째 : "+ participant[i]+" / 총 비교 대상 수 : "+comparelist.size());

            loopJ:
            for (int j = 0; j < comparelist.size(); j++) {
                System.out.println("================================\n비교 대상 "+ compare + "와 " + comparelist.get(j));
                if(compare==comparelist.get(j)){
                    comparelist.remove(j);
                    System.out.print("동일 대상을 삭제\n================================\n");
                    count++;
                    break loopJ;
                }
                else{
                    System.out.println("대상을 삭제안함");
                }
                if(comparelist.size()==1){
                    break loopJ;
                }
            }

            if (count != 1){
                answer=compare;
                break loopI;
            }
            count=0;
        }
        System.out.println("\n********************************\n못나온자 : "+ answer +"\n********************************\n");
        return answer;
    }
}

public class Main {
    public static void main(String[] args) {
        Solution sol = new Solution();

        //String[] participant1 = {"leo","kiki","eden"};
        //String[] completion1 = {"eden","kiki"};

        String[] participant2 = {"marina", "josipa", "nikola", "vinko", "filipa"};
        String[] completion2 = {"josipa", "filipa", "marina", "nikola"};

        String[] participant3 = {"mislav", "stanko", "mislav", "ana"};
        String[] completion3 = {"stanko", "ana", "mislav"};

        //String result1 = sol.solution(participant1,completion1);
        String result2 = sol.solution(participant2,completion2);
        String result3 = sol.solution(participant3,completion3);

        System.out.println("\n결과창");
        //System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
    }
}

 

21. 이상한 문자 만들기

프로그래머스에서 오류.

이유를 못찾았음 > 입력받는 문자열 끝에 공백이 여러개 있다면 인식되지 않음. (2021-11-11)

 

참고자료

charAt()

https://colossus-java-practice.tistory.com/31

 

toUpperCase(), toLowerCase()

https://pridiot.tistory.com/24

 

String .split()

https://jamesdreaming.tistory.com/84

 

실패본

더보기

import java.util.*;

class Solution {
public String solution(String s) {
String answer = "";
String[] str = s.split(" ");
char tmp;

for(int i=0;i<str.length;i++){
for(int cnt=0;cnt<str[i].length();cnt++){
if(cnt%2==0){
tmp=str[i].charAt(cnt);
answer += s.valueOf(tmp).toUpperCase();
}
else{
tmp=str[i].charAt(cnt);
answer += s.valueOf(tmp).toLowerCase();
}
}
if(i < str.length-1){
answer += " ";
}
}
return answer;
}
}

public class Main {
public static void main(String[] args) {
Solution sol = new Solution();

String s1 = "try hello world";

String result1 = sol.solution(s1);

System.out.println(result1);
}
}

완성본

split 으로 나누는 절차는 필요하지만, 맨 뒤쪽의 문자열이 공백인 경우 에러 발생. (나눠줄 다음 문자열이 없어서)

해결을 위해 String 배열을 " " 공백으로 나누는 것이 아닌, 문자 하나씩으로 배치하여 공백칸도 배열로 받음.

이후 공백 칸이 나오게 된다면 공백칸 때는 배열의 문자 대소구분을 0으로 초기화 해주어, 처음 나오는 문자의 경우 대문자로 인식 될 수 있도록 조건을 줌.

 

https://www.quora.com/What-does-this-line-%E2%80%9Cfor-int-I-arr-%E2%80%9D-means-in-Java-Here-arr-is-an-array

class Solution {
    public String solution(String s) {
        String answer = "";
        String[] str = s.split("");
        int cnt=0;
        char tmp;

        for(int i=0;i<str.length;i++){
            System.out.println(str[i]);
            tmp=str[i].charAt(0);
            if(cnt%2==0 && str[i]!=""){
                answer += s.valueOf(tmp).toUpperCase();
                cnt++;
            }
            else{
                answer += s.valueOf(tmp).toLowerCase();
                cnt++;
            }
            if(tmp == ' '){
                cnt=0;
            }
        }
        return answer;
    }
}
public class Main {
    public static void main(String[] args) {
        Solution sol = new Solution();

        String s1 = "  try  hello              world     ";

        String result1 = sol.solution(s1);

        System.out.println(result1);

    }
}