프라이D
프라이Develog(❁´◡`❁)
프라이D
전체 방문자
오늘
어제
  • ALL (378)
    • TDD, Cleancode with JavaScr.. (5)
    • 프로젝트 (32)
      • work (3)
      • 직접 만드는 기술 블로그 (2)
      • 데일리 옥션 (19)
      • 모락모락 (8)
    • Computer Science (1)
    • Algorithm & 자료구조 (94)
      • 알고리즘 w.JavaScript (53)
      • 자료구조 (5)
      • (인프런) 자바스크립트 알고리즘 문제풀이 (34)
    • JavaScript (45)
      • JavaScript (41)
      • 모던 자바스크립트 Deep Dive (4)
    • WEB (13)
    • 회고 (12)
    • TIL (109)
    • WIL (7)
    • Stacks (20)
      • React.js (6)
      • Next.js (1)
      • Redux (3)
      • Node.js (2)
      • GIT (2)
      • SAP (1)
    • 15일 메이킹 프로젝트 (15)
    • 이전 기록 (14)
    • ETC. (5)
    • ---------------2021 (6)
      • 내일배움단-웹개발 5주 (2)
      • 정보처리기사 (4)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 자바스크립트비트마스크
  • 코드스테이츠
  • 자바스크립트알고리즘
  • Til
  • nomadcoder
  • 스파르타코딩클럽
  • MySQL
  • 내일배움카드
  • 비트마스크
  • 내일배움단
  • 2023 인프콘 후기
  • 투포인터알고리즘
  • 모던자바스크립트딥다이브
  • 코딩프로젝트
  • nomadcoders
  • vanilaJS
  • 자바스크립트
  • JavaScript
  • 국비지원
  • 알고리즘

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
프라이D

프라이Develog(❁´◡`❁)

Algorithm & 자료구조/알고리즘 w.JavaScript

[Leetcode] 1071. Greatest Common Divisor of Strings

2023. 12. 28. 00:31
 

Greatest Common Divisor of Strings - LeetCode

Can you solve this real interview question? Greatest Common Divisor of Strings - For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return t

leetcode.com

For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

 

풀이

var gcdOfStrings = function (str1, str2) {
  if (str1 + str2 !== str2 + str1) return '';

  const getGcd = (num1, num2) => {
    while (num2 !== 0) {
      let temp = num2;
      num2 = num1 % num2;
      num1 = temp;
    }

    return num1;
  };

  const gcd = getGcd(str1.length, str2.length);

  return str1.slice(0, gcd);
};
  • 처음엔 최대공약수로 접근해야 된다는 생각을 못했음. => 왜냐면 문자열 중간부터 겹치는 부분이 나타날 수도 있으니까
  • 근데 문제를 다시 보니 그런 케이스가 아니라, 같은 문자열 패턴의 반복으로 이어지는 문제였음.
  • 그래서 최대공약수를 구하고 그 길이로 문자열을 잘라 리턴함

 

 추가된 풀이

let getGCD = (num1, num2) => {
    let gcd = 1;

    for(let i=2; i<=Math.min(num1, num2); i++){
        if(num1 % i === 0 && num2 % i === 0){
            gcd = i;
        }
    }

    return gcd;
}

var gcdOfStrings = function(str1, str2) {

    if (str1 + str2 !== str2 + str1) return '';

    const gcd = getGCD(str1.length, str2.length);
    const shortest = str1.length > str2.length ? str1 : str2;
    const common = shortest.substring(0,gcd);

    return common;
};
  •  gcd 를 구한 것은 좋은데 굳이 shortes 랑 common 같은 변수를 선언할 필요는 없었던 것 같음.
저작자표시

'Algorithm & 자료구조 > 알고리즘 w.JavaScript' 카테고리의 다른 글

[Leetcode] 605. Can Place Flowers  (0) 2023.12.31
[Leetcode] 1431. Kids With the Greatest Number of Candies  (0) 2023.12.31
[Leetcode] 1768.Merge Strings Alternately  (2) 2023.12.18
[알고리즘 JS] Sliding window - 중복이 없는 가장 긴 문자열의 길이 찾기  (0) 2023.03.24
[알고리즘JS] 피로도 (프로그래머스 lv.2)  (0) 2023.02.04
    'Algorithm & 자료구조/알고리즘 w.JavaScript' 카테고리의 다른 글
    • [Leetcode] 605. Can Place Flowers
    • [Leetcode] 1431. Kids With the Greatest Number of Candies
    • [Leetcode] 1768.Merge Strings Alternately
    • [알고리즘 JS] Sliding window - 중복이 없는 가장 긴 문자열의 길이 찾기
    프라이D
    프라이D
    틀린내용 정정 및 개선사항은 언제든지 댓글 달아주세요 :D

    티스토리툴바