반응형

map에 문자와 누르는 횟수를 저장해서 

없으면 횟수 탐색하는 함수를 돌리도록 했는데

keymap의 길이가 최대 100이라 그런지 성능차이가 미미했음.

import java.util.*;
class Solution {
    String[] keymap;
    public int[] solution(String[] keymap, String[] targets) {
        this.keymap = keymap;
        int[] answer = new int[targets.length];
        HashMap<String, Integer> key = new HashMap<>();
        //목표 문자열 순회
        for(int i=0;i<targets.length;i++){
            String target = targets[i]; //목표문자열
            int j=0;
            int count=0;
            while(j<target.length()){ //목표 문자열의 문자 탐색 ABCD
                String str = target.charAt(j)+"";
                int cnt = key.getOrDefault(str,0);
                if(cnt==0){ //map에 담긴 횟수가 없으면 찾기
                    cnt = findCount(str);
                }
                key.put(str,cnt);
                if(cnt == -1){
                    count = -1;
                    break;
                }
                count += cnt;
                j+=1;
            }
            answer[i] = count;
        }
        return answer;
    }
    
    //알파벳을 누르기 위한 최소한의 횟수 리턴
    public int findCount(String str){
        int minKey = 100;
        for(int i=0;i<keymap.length;i++){
            String key = keymap[i];
            int index = key.indexOf(str);
            if(index == 0){ //1번만 눌러도 되면 1 리턴
                return 1;
            }else if(index == -1){ //없으면 다음 키 탐색
                continue;
            }else{
                minKey = Math.min(index,minKey);
            }
        }
        if(minKey == 100 ){
            return -1;
        }else{
            return minKey += 1; //인덱스보다 1번 더 눌러야함
        }
    }
}

map 사용했을때 / map 사용 안 했을 때

누를 문자가 중복이 많고 길이가 길면 map을 쓰는게 낫겠지만은

이런 경우는 굳이 map 안쓰고 가독성을 잡는게 나을지도

반응형
반응형

써본것

정규식 정말 오랜만에 써봤음

[^ ] : 안에 있는 문자 제외하고. 대괄호 안에서는 이스케이프 처리 하지 않아도 됨

.{2,} : .이 두번 이상

^. : .으로 시작

.$ : .이 끝에 위치

isEmpty() : 문자열 빈 것 체크 

 

class Solution {
    public String solution(String new_id) {
        //1단계 new_id의 모든 대문자를 대응되는 소문자로 치환합니다.
        new_id = new_id.toLowerCase();
       
        //2단계 new_id에서 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다.
        new_id = new_id.replaceAll("[^a-z0-9\\-\\_\\.]","");
        
        //3단계 new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다.
        new_id = new_id.replaceAll("\\.{2,}",".");  
        
        //4단계 new_id에서 마침표(.)가 처음이나 끝에 위치한다면 제거합니다.
        new_id = new_id.replaceAll("^\\.|\\.$","");
        
        //5단계 new_id가 빈 문자열이라면, new_id에 "a"를 대입합니다.
        if("".equals(new_id)){
            new_id = "a";
        }
        //if(new_id.isEmpty())
        
        //6단계 new_id의 길이가 16자 이상이면, new_id의 첫 15개의 문자를 제외한 나머지 문자들을 모두 제거합니다.
        if(new_id.length() >= 16){
            new_id = new_id.substring(0,15);
        }
        
        //만약 제거 후 마침표(.)가 new_id의 끝에 위치한다면 끝에 위치한 마침표(.) 문자를 제거합니다.
        new_id = new_id.replaceAll("\\.$","");
        
        //7단계 new_id의 길이가 2자 이하라면, new_id의 마지막 문자를 new_id의 길이가 3이 될 때까지 반복해서 끝에 붙입니다.
        if(new_id.length() <= 2){
            String lastLetter = new_id.charAt(new_id.length()-1)+"";
            while(new_id.length() < 3){
                new_id += lastLetter;  
            }
        }
        return new_id;
    }
}
반응형
반응형

새로운것

result
    .stream()    //스트림의 각 요소를 주어진 함수를 통해 새로운 스트림으로 반환
    .mapToInt(Integer::intValue)	//객체 스트림을 int 스트림으로 변환
    .toArray(); 		//스트림을 배열로

 

import java.util.*;
import java.util.stream.*;

//비교 시에 Date 라이브러리 쓰면 안 됨(한 달 28일로 가정하므로)
//계약일시 + 유효기간 합에서 단순히 12를 나눠서 계산하면 12월인경우 곤란해짐
class Solution {
    int todayDay; 
    int todayMonth;
    int todayYear;
    public int[] solution(String today, String[] terms, String[] privacies) {
        this.todayDay = Integer.parseInt(today.split("\\.")[2]);
        this.todayMonth = Integer.parseInt(today.split("\\.")[1]);
        this.todayYear = Integer.parseInt(today.split("\\.")[0]);
        
        Map<String,Integer> termsMap = new HashMap<>();
        for(String term : terms){
            termsMap.put(term.split(" ")[0],Integer.parseInt(term.split(" ")[1]));
        }
        
        List<Integer> result = new ArrayList<>();
        for(int i=0;i<privacies.length;i++){
            String start = privacies[i].split(" ")[0];
            int duration = termsMap.get(privacies[i].split(" ")[1]);
            if(!isOK(start,duration)){
                result.add(i+1);
            }
        }
        
        return result.stream().mapToInt(Integer::intValue).toArray();
    }
    
    //모든 달은 28일로 가정
    public boolean isOK(String start, int duration){
        int dueDay = Integer.parseInt(start.split("\\.")[2]);
        int dueMonth = Integer.parseInt(start.split("\\.")[1]) + duration;
        int dueYear = Integer.parseInt(start.split("\\.")[0]);        

        while(dueMonth > 12){
            dueMonth -= 12;
            dueYear += 1;
        }
        
        
        if(dueDay == 1){
            dueDay = 28;
            if(dueMonth == 1){
                dueMonth = 12;
                dueYear -= 1;
            }else{
                dueMonth -= 1;
            }
        }else{
            dueDay -= 1;
        }
        
        
        
        
        if(dueYear < todayYear){
            return false;
        }else if(dueYear > todayYear){
            return true;
        }else{
            if(dueMonth < todayMonth){
                return false;
            }else if(dueMonth > todayMonth){
                return true;
            }else{
                if(dueDay < todayDay){
                    return false;
                }else{
                    return true;
                }
            }
        }
    
        
    }
}
반응형
반응형

오랜만에 발견한 정말 재밌는 소설
역사적 사실을 기반으로 한 허구소설
일제 강점기 치하 당대 지식인, 지역 유지, 기생, 건달의 삶을 그려냄.
인물들의 어릴적부터 최후까지 줄거리를 따라 함께하기에 삶의 허무함도 느껴지고 애잔하기도 하다.
이야기 서술이 흡입력있고 전개가 빨라서 지루하지도 않고 분량이 제법 되는 것 같은데 정말 빠르게 읽을 수 있었다.
독립운동하는 내용도 있어 뭉클하였고, 각자가 처한 작금에 대한 입장과 삶에 대한 태도와 가치관을 읽는 재미도 있었다. 근데 이제 사랑의 낭만을 곁들인..
어떻게 이런책을 미국에서..
정말정말 재미있었고 드라마나 영화로 나와도 너무 좋을 것 같음!

+
내용 중 옥희가 [그 일이 너와 나보다 중요하지 않니] 라고 했을때 정호가 갑자기 돌변하며 옥희한테 버럭했던 장면이 있는데 그 부분은 좀 의아했다. 그렇게 화를 낼만한 대사인지? 한순간에 옥희에 대한 마음을 단단히 접고 돌아설만한 대사였는지? 공감이 좀 안돼서 의아했다ㅎㅎ

반응형

'' 카테고리의 다른 글

친애하는 숙녀 신사 여러분 - 유즈키 아사코  (0) 2023.04.16
인간의 법정 - 조광희  (0) 2022.08.27
완전한 행복 - 정유정  (0) 2022.05.07
매일 인문학 공부 - 김종원  (2) 2021.11.03
포르노랜드 - 게일 다인스  (0) 2021.10.14
반응형

새로 써본것

Arrays.fill(array,value);

Arrays.fill(seconds, bandage[1]);

 

 

풀어본 방법 1

각 초에 대해 회복 action을 넣어뒀음.

int[] seconds를 1000개짜리로 초기화하니까 런타임에러가 났다. 너무 오래걸리나보다..

import java.util.*;

class Solution {
    public int solution(int[] bandage, int health, int[][] attacks) {
        int answer = 0;
        int lastSec = attacks[attacks.length-1][0];
        int[] seconds = new int[lastSec+1];      
        int plusHealth = bandage[2];
        Arrays.fill(seconds, bandage[1]); //기본회복량으로 fill
        for(int i=0; i< attacks.length ; i++){
            seconds[attacks[i][0]] =  attacks[i][1] * -1; //해당 초에 데미지 넣기
        }
        
        int count = 0;
        int max = health;
        for(int i=1;i<=lastSec;i++){
            if(seconds[i] < 0){
                //공격
                health += seconds[i];
                count = 0;
                if(health<=0) return -1;
            }else{
                health += seconds[i];
                count += 1;     
               
                if(count == bandage[0]){
                    health += plusHealth;
                    count = 0;
                }               
                //최대체력인지검사
                health = Math.min(max,health);
            }
        }
        return health <= 0 ? -1 : health;
    }
}

//각 초의 action
//공격을받거나
//회복스킬 count
반응형
반응형

배운것 

1. stream 연습~~

- stream은  util에서 퉁치면 안되고 따로 import 해줘야한다.

import java.util.*;
import java.util.stream.*;

 

- distinct() 사용

요소의 중복을 제거.

리턴 타입 : Stream, IntStream, LongStream, DoubleStream 

public class DistinctExample {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 3}; // int[] 배열

        // int[]에서 중복을 제거하고 List<Integer>로 변환
        List<Integer> distinctList = Arrays.stream(nums) // int[]에서 IntStream으로 변환
            .distinct() // 중복 제거
            .boxed() // int를 Integer로 변환
            .collect(Collectors.toList()); // List<Integer>로 수집

        System.out.println(distinctList); // [1, 2, 3] 출력
    }
}

 

- filter() 사용

매개값으로 주어진 Predicate가 true를 리턴하는 요소만 필터링

List<String> nameList = reportList
                                .stream()
                                .filter(rep -> rep.startsWith(id+" "))
                                .map(repp -> repp.split(" ")[1])
                                .collect(Collectors.toList());

 

- count() 사용

요소 개수 반환 

리턴타입 : long

long cnt = nameList
                .stream()
                .filter(reportee -> reporteeCount.getOrDefault(reportee,0) >= k)
                .count();

 

 

2. startsWith(), endsWith()  사용해봄

써본적이 없는데 써봤다.

boolean startsWith(String str)
boolean endsWith(String str)

 

 

두번째 다른방법으로 풀기

다른사람 답안을 보면서 따라해봤다.

제일 오래걸린 시간 : 테스트3 (6000.64ms, 555MB)

뭐야 더오래걸림

report 길이가  1 ~ 200,000 인데 아무리 중복을 제거했어도 두번돌아서 그런가

import java.util.*;
import java.util.stream.*;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        //1. report에서 중복을 제거
        List<String> reportList = Arrays.stream(report)
            .distinct()
            .collect(Collectors.toList());
        
        //2. id별로 신고당한 횟수를 누적한다.
        HashMap<String,Integer> reporteeCount = new HashMap<>();
        for(String rep : reportList){
            String reportee = rep.split(" ")[1];
            int cnt = reporteeCount.getOrDefault(reportee,0);
            reporteeCount.put(reportee,cnt+1);
        }
        
        //3. id 돌면서 메일 횟수 카운트
        int[] answer = new int[id_list.length];
        answer = Arrays.stream(id_list)
            .mapToInt(id ->{ //id별 처리
                //사용자가 신고한 리스트
                List<String> nameList = reportList
                                .stream()
                                .filter(rep -> rep.startsWith(id+" ")) //비슷한 이름 방지
                                .map(repp -> repp.split(" ")[1])
                                .collect(Collectors.toList());
                
                //사용자가 신고한 리스트에서 k 가 넘는 요소의 개수 산출
                long cnt = nameList.stream()
                                    .filter(reportee -> reporteeCount.getOrDefault(reportee,0) >= k)
                                    .count();
                return (int)cnt;
                }).toArray();

        return answer;  
    }  
}

 

 

 

 

첫번째 풀었던 것

제일 오래걸린시간 : 테스트21 (311.44ms, 164MB)

import java.util.*;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        HashMap<String,Set<String>> reporterList = new HashMap<>();
        for(String rep : report){
            String reporter = rep.split(" ")[0]; //신고한사람 muzi
            String reportee = rep.split(" ")[1]; //신고당한사람 frodo
            
            //ID당 유저가 신고한 ID들
            Set<String> temp = reporterList.getOrDefault(reporter,new HashSet<String>());
            temp.add(reportee);
            reporterList.put(reporter,temp);        
        }
        
        //신고당한 id별로 횟수 정리
        HashMap<String,Integer> reporteeCount = new HashMap<>();
        Collection<Set<String>> reportees = reporterList.values();
        //ArrayList<String> bannedIds = new ArrayList<>(); //정지된 id
        for(Set<String> list : reportees){
            for(String name : list){
                int cnt = reporteeCount.getOrDefault(name,0);
                reporteeCount.put(name,cnt+1);
                //if(cnt >= k) bannedIds.add(name);
            }
        }
        
        int[] answer = new int[id_list.length];
        //정지된 신고 리스트 id가 정지되었나 검사
        for(int i=0; i<id_list.length;i++){
            String id = id_list[i];
            Set<String> reportList = reporterList.getOrDefault(id,new HashSet<String>());
            int mailCnt = 0;
            //신고 리스트에 있는 아이디가 정지되었나 검사
            for(String reportee : reportList){
                if(reporteeCount.getOrDefault(reportee,0) >= k ){
                    mailCnt += 1;
                }
            }
            answer[i] = mailCnt;
        }
        
      
        return answer;
    }
    

    

}

//사용자 누적 신고 횟수 k번 이상시 
//동일 유저에 대한 신고 횟수 중복제거 어떻게
//신고자에게 메일

//1. report 돌면서 id별로 누구를 신고했는지 정리(중복x) HashMap<String,Set<>>;
    //예 "muzi" <frodo, apeach>
//2. HashMap 돌면서 id별 신고당한 누적횟수 정리 HashMap, 3회 이상인경우 arraylist에 추가
    //예 "muzi", 3   ["muzi","frodo"]
//3. id list 돌면서 신고list꺼내서 배열에 있는지 확인하여 메일 횟수 ++

 

 

 

반응형
반응형

조건에 맞는걸 중간부터 찾으려고 했음 -> 넘 어려움

배열이 주어지면 배열을 앞에나 뒤부터 순회하는게 젤 나은듯

import java.util.*;

class Solution {
    public int solution(int[] citations) {
        int h = citations.length;
        Arrays.sort(citations);
        
        /*배열 순회하기
        for(int c : citations){
            if(c >= h){
                return h;
            }else{
                h -= 1;
            }
        }
        return h;
        */
        
        //길이기준 순회
        int index = 0;
        for(int i=h;i>0;i--){
            if(citations[index] >= i){
                return i;
            }else{
                index +=1;
            }
        }
        return 0;

    }
}
//,0,0]
//h=3 index=0;
//h=2 index 1;
//h=1

//길이 7 
//[1,2,3,5,6,7,8]
//뒤에부터 
//h = 7 일때 index[0] 1 의 값이 7이상이냐? 
//h = 6 일때 index[1] 2 의 값이 6이상이냐?
//h = 5 일때 index[2] 3 의 값이 5 이상이냐?
//h= 4 일때 index[3] 5의 값이 4 이상이냐? -> h반환

//index[0] 일때 h=len index[]의 값이 h 이상이냐?
//index[1]일때 h= len-1

//배열 -> 배열기준순회
반응형
반응형

개선할점

- 반복문 쓸 때 길이조건 변수 헷갈리지 말고 제대로 좀 넣어야한다.

- char 타입데이터에 int 더하면 int 나오니까 (char) 형변환 

class Solution {
    public String solution(String s, String skip, int index) {
        StringBuilder result = new StringBuilder();
        for(int i=0;i<s.length();i++){
           result.append(getAlphabet(s.charAt(i),skip,index));
        }
        return result.toString();
    }
    
    //index만큼 뒤에 있는 알파벳 찾기. skip에 있는거 빼고.
    public String getAlphabet(char c, String skip, int index){ 
        int count = 0 ;
        char standardChar = c; //standardChar = 'x' , count 4 
        while(true){
            char nextChar = standardChar == 'z' ?  'a' : (char)(standardChar + 1);//y
            standardChar = nextChar; //y
            //skip에 없으면
            if(skip.indexOf(Character.toString(nextChar)) == -1){
                count += 1;
            }
            
            if(count == index){
                break;
            }
        }
        
        return Character.toString(standardChar);
    }
}



//charAt(i) 문자 +1반복.. count index만큼 채울때까지..
//기준문자는 계속 바꾼다 
//문자가 z라면.. a로바꾸고..
반응형
반응형

개선할점

HashMap 초기화 하지 않고 put 메서드 호출하려 하면 nullPointException 나므로 조심.

메서드 나누니까 편하긴 하다

import java.util.*;
class Solution {
    String mainHand;
    int[] leftPosition = {1,4};
    int[] rightPosition = {3,4};
    HashMap<Integer,int[]> phone = new HashMap<>();
    
    public String solution(int[] numbers, String hand) {
        mainHand = hand.equals("right")? "R" : "L";
        phone.put(1,new int[]{1,1});
        phone.put(2,new int[]{2,1});
        phone.put(3,new int[]{3,1});
        phone.put(4,new int[]{1,2});
        phone.put(5,new int[]{2,2});
        phone.put(6,new int[]{3,2});
        phone.put(7,new int[]{1,3});
        phone.put(8,new int[]{2,3});
        phone.put(9,new int[]{3,3});
        phone.put(0,new int[]{2,4});
        
        StringBuilder answer = new StringBuilder();
        for(int i=0;i<numbers.length;i++){
            answer.append(getHand(numbers[i]));
        }
       
        return answer.toString();
    }
    
    
    //어느 손으로 누를지 계산 -> 현재위치 이동하기
    public String getHand(int num){
        String leftOrRight = switch(num){
                case 1,4,7 -> "L";
                case 3,6,9 -> "R";
                case 2,5,8,0 -> whenMiddle(num);
                default -> mainHand;
        };
        //손 이동하기 
        makePosition(num,leftOrRight);
        
        return leftOrRight;
    }
        
    //가운데일때 어느손으로 누를지 계산
    public String whenMiddle(int num){
        int[] numPosition = phone.get(num);
        int leftHandDistance = Math.abs(leftPosition[0]-numPosition[0])
                            + Math.abs(leftPosition[1]-numPosition[1]);
        int rightHandDistance = Math.abs(rightPosition[0]-numPosition[0])
                            + Math.abs(rightPosition[1]-numPosition[1]);
    
        if(leftHandDistance == rightHandDistance){
            return mainHand;
        }else if(leftHandDistance  < rightHandDistance){
            return "L";
        }else{
            return "R";
        }
    }
    
    //현재위치 이동하기    //누를 숫자   //누를 손
    public void makePosition(int num, String whatHand){
        if(whatHand.equals("L")){
            leftPosition = phone.get(num);
        }else{
            rightPosition = phone.get(num);
        }
    }
}

//현재위치 [1,3],[2,4]이렇게
//현재위치 lefthand=4   1->1, 4->2, 7->3, *->4
//현재위치 righthand=4  3->1, 6->2, 9->3, #->4
//숫자가 1,4,7이면 -> L 
//숫자가 3,6,9이면 -> R 
//숫자가 2,5,8,0이면 2->1, 5->2, 8->3, 0->4 로 해서 가까운걸로 같으면 hand 참고
//가운데 누르고 난뒤
반응형
반응형

틀린 이유

1. substring(start, end) 인덱스 헷갈림

//i부터 맨뒤까지 모두 자르기
str.substring(i);
str.substring(i,str.length);

//end보다 하나 전까지 가져옴

2. 오류파악 String index out of range: 0 

-> index0 도 없다는건 길이가 0이라는것. substring 결과의 길이가 0일때의 케이스 고려를 안 함

반응형

+ Recent posts