Section3_4번: 가장 짧은 문자거리
-------강의 풀이------
목표 문자와의 양쪽 거리 확인하는 법
:앞에서부터 for문 돌면서 왼쪽과의 거리 체크
뒤에서부터 for문 돌면서 오른쪽과의 거리 체크.
둘 중 작은 값 가져오기.
*주의!!) 거리 체크용 변수의 초기값은=큰값(ex.문자열 길이보다 큰 1000)으로 설정해야한다.
맨 앞 문자 거리가 잘못 계산될 수 있음! ( ex. abcba 에서 c체크)
t e a c h e r m o d e
0 0 1 2 3 0 1 2 3 4 0 ->
1 0 3 2 1 0 4 3 2 1 0 <-
둘 중 작은 숫자로 재할당
function solution3_4(str: string, t: string): string {
let answer:number[] = [];
let cnt = 1000;
for(let i=0; i<str.length; i++){
if(str[i] !== t)cnt++;
else cnt=0;
answer.push(cnt) ;
}
cnt = 1000;
for(let i=str.length-1; i>=0; i--){
if(str[i] !== t){
cnt++;
answer[i] = Math.min(answer[i],cnt);
}else {
cnt=0;
}
}
return answer.join(" ");
}
console.log(solution3_4("teachermode", "e"));
Section3_5번: 문자열 압축
function solution3_5(str: string): any {
let answer =str[0];
let count = 1;
for (let i=1; i<str.length; i++){
//앞에랑 같은 문자일때
if(str[i]===str[i-1]){
count ++;
//앞에랑 다른 문자고 count 쌓여있을때
}else if (count!==1 && str[i]!==str[i-1]) {
answer += count.toString();
answer += str[i];
count =1;
// count도 1이고 다른문자일때
}else answer += str[i];
}
return answer;
//----------강의 풀이-------------
for (let i=1; i<str.length; i++){
//앞에랑 같은 문자일때
if(str[i]===str[i-1])count ++;
//앞이랑 다른 문자일때
else{
answer += str[i];
if(count!==1) answer += count.toString();
count =1;
}
}
return answer;
}
console.log(solution3_5("KKHSSSSSSSE"));
나는 i=1부터 시작, 강의 풀이는 문자열 맨 뒤에 빈문자 추가하고 length-1 미만까지 탐색
'알고리즘(with TS)' 카테고리의 다른 글
알고리즘 풀이 4)4-5 (완전탐색-블루투포스) & TS(unknown타입, Set타입) (0) | 2023.01.29 |
---|---|
알고리즘 풀이 4)1-3 (완전탐색-블루투포스) (0) | 2023.01.23 |
알고리즘 풀이 2)6-7, 3)1-3 & TS(isNaN 사용시 주의할 부분) (0) | 2023.01.19 |
알고리즘 풀이 2)1-5 (1) | 2023.01.17 |
알고리즘 풀이 1)15-17번 (0) | 2023.01.14 |