728x90
반응형
https://github.com/ROUTINE-STUDY/Algorithm
ROUTINE-STUDY/Algorithm
초보 알고리즘 스터디 / 누구나 참여 가능 :runner:. Contribute to ROUTINE-STUDY/Algorithm development by creating an account on GitHub.
github.com
알고리즘 스터디를 진행하고 있습니다.
초보들로 구성되어있으며, 열심히 풀어보고 풀이 방식을 공유하고 피드백을 해주는 스터디입니다.
문의는 댓글 혹은 GitHub 주소를 참고해주세요.
문제 출처 : https://leetcode.com/problems/keyboard-row/
Keyboard Row - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 설명
문자열 배열 words가 주어지고, 해당 문자열이 키보드의 한 행에서만 입력이 될 수 있는 문자열들을 반환하세요.
키보드 한 행 : ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
word : "qwer" = true, "qaz" = false
풀이 방법
정규표현식을 활용하여 풀이했습니다.
정규식을 만들어서 배열에 저장 한 뒤 검사하여 3가지 케이스 모두 일치하지 않으면 삭제합니다.
1. words 배열을 List 형태로 변환
2. 삭제 시 인덱스를 유지하기 위해 list의 마지막부터 반복
3. 정규표현식 검사 후 일치하지 않으면 list에서 삭제
내 코드(JAVA)
public String[] findWords(String[] words) {
String[] patterns = new String[]{"^[qwertyuiop]*$", "^[asdfghjkl]*$", "^[zxcvbnm]*$"};
List<String> list = new ArrayList<>(Arrays.asList(words));
for(int i=list.size()-1; i>=0; i--) {
String word = list.get(i).toLowerCase();
boolean isMatch = false;
for(String pattern : patterns) {
if(Pattern.matches(pattern, word)) {
isMatch = true;
break;
}
}
if(!isMatch) list.remove(i);
}
return list.size() > 0 ? list.toArray(new String[list.size()]) : new String[]{};
}
스터디 피드백 내용
1. list의 요소가 변화하지 않게 뒤에서부터 순회한 방법이 좋은 것 같다.
2. return 시 list의 size를 체크하지 않아도 된다. list의 size가 0이라면 자동으로 빈 list가 생성됨
return list.toArray(new String[list.size()]);
728x90
반응형
'알고리즘' 카테고리의 다른 글
[LeetCode/JAVA] 58. Length of Last Word (0) | 2021.07.18 |
---|---|
[LeetCode/JAVA] 66. Plus One (0) | 2021.07.18 |
[LeetCode/JAVA] 14. Longest Common Prefix (0) | 2021.07.17 |
[LeetCode/JAVA] 637. Average of Levels in Binary Tree (0) | 2021.07.17 |
[LeetCode/JAVA] 389. Find the Difference (0) | 2021.07.17 |
댓글