전체 글 (262)
2022-01-05 00:03:32
반응형

Same Tree

 

 문제 설명

 

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

 

 제한 사항

 

  • The number of nodes in both trees is in the range [0, 100].
  • -104 <= Node.val <= 104

 

 입출력 예

 

input output
p = [1, 2, 3] , q = [1, 2, 3] True
p = [1, 2] , q = [1, null, 3] False
p = [1, 2, 1] , q = [1, 1, 2] False

 

 Python 코드

 

Python 8ms code 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution(object):
    def isSameTree(self, p, q):
     
        if not p and not q:
            return True
        if not p or not q:
            return False
        
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
  • isSameTree( )는 왼쪽의 서브 트리와 오르른쪽의 서브트리가 동일한지를 판단하는 재귀함수

* 참고 링크 : https://velog.io/@wisepine/Leetcode-Same-Tree

 

 C++ 코드

 

C ++ 100% 0ms code

- String으로 바꾸지 않고 맨 뒤의 값과 맨 앞의 값을 비교하면서 푼 코드

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p == NULL && q == NULL) // if the two nodes are empty nodes, return true
            return true;
        else if((p == NULL && q != NULL) || (p != NULL && q == NULL)) // if only one of the nodes from p and q is emtpy, 2 trees are not equal
            return false;
        else 
            return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
						// First we compare the values in each node from p and q. Then, use a recursive method, call isSameTree function with left nodes of p and q as parameters. Do the same for the right nodes.
    }
};

* 참고 링크 : https://leetcode.com/problems/same-tree/discuss/166896/C++-solution-beats-100

 

 출처

 

https://leetcode.com/problems/same-tree/submissions/

반응형
2022-01-04 23:13:28
반응형

Palindrome Number

 

 문제 설명

 

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

  • For example, 121 is a palindrome while 123 is not.

 

 제한 사항

 

  • -231 <= x <= 231 - 1

 

 입출력 예

 

x return
121 True
-121 False
10 False

 

 Python 코드

 

  • int를 문자열로 변환

 

135ms code Python

class Solution:
    def isPalindrome(self, x: int) -> bool:
        return str(x) == str(x)[::-1]

 

56ms code Python

class Solution:
    def isPalindrome(self, x: int) -> bool:
        return False if x < 0 else str(x) == str(x)[::-1]

 

* 참고 링크 1 : https://hackmd.io/@y56/Hk6PWb7mr?type=view 

* 참고 링크 2 : https://dhairya2136.medium.com/leetcode-9-palindrome-number-python-bdcd99bd7068

 

* Python Array [ :: ] 용법

arr[::], arr[1:2:3], arr[::-1] 등으로 배열의 index에 접근하는 방법을 Extended Slices(확장형 슬라이스)라고 한다.

arr[A:B:C]의 의미는, index A 부터 index B 까지 C의 간격으로 배열을 만들어라는 말입니다.
- A가 None 이라면, 처음부터 라는 뜻
- B가 None 이라면, 할 수 있는데까지
- C가 양수라면 마지막 index까지, C가 음수라면 첫 index까지가 된다.
- 마지막으로 C가 None 이라면 한 칸 간격으로 라는 뜻
arr = range(10) 
arr 
# result : [0,1,2,3,4,5,6,7,8,9] 

arr[::2] # 처음부터 끝까지 두 칸 간격으로 
# result : [0,2,4,6,8] 

arr[1::2] # index 1 부터 끝까지 두 칸 간격으로 
# result : [1,3,5,7,9] 

arr[::-1] # 처음부터 끝까지 -1칸 간격으로 ( == 역순으로) 
# result : [9,8,7,6,5,4,3,2,1,0] 

arr[::-2] # 처음부터 끝까지 -2칸 간격으로 ( == 역순, 두 칸 간격으로) 
# result : [9,7,5,3,1] 

arr[3::-1] # index 3 부터 끝까지 -1칸 간격으로 ( == 역순으로) 
# result : [3,2,1,0] 

arr[1:6:2] # index 1 부터 index 6 까지 두 칸 간격으로 
# result : [1,3,5]

* 참고 링크 1 : https://blog.wonkyunglee.io/3

* 참고 링크 2 : https://docs.python.org/release/2.3.5/whatsnew/section-slices.html

* is_palindrome ( ) 함수 : 회문 판별 함수

palindrome(회문)은 순서를 거꾸로 읽어도 제대로 읽은 것과 같은 단어와 문장을 의미한다.
예를 들어 "level", "SOS", "rotator", "nurses run"과 같은 단어와 문장이 있다.
def is_palindrome(word):
    return word[::-1]==word

# True
print( is_palindrome("kayak") )
print( is_palindrome("madam") )
print( is_palindrome("racecar") )
print( is_palindrome("abradacadarba") )
print( is_palindrome("토마토") )

# False
print( is_palindrome('hello') )
print( is_palindrome('coffee') )

* 참고 링크 1 : https://zetawiki.com/wiki/%ED%95%A8%EC%88%98_is_palindrome() 

* 참고 링크 2 : https://dojang.io/mod/page/view.php?id=2331 

 

 C++ 코드

 

class Solution {
public:
    bool isPalindrome(int x) {
        string temp = std::to_string(x);
        int left = 0;
        int right = temp.size()-1;
        while(left<=right)
        {
            if(temp[left++]!=temp[right--])
                return false;
        }
        return true;
    }
};

 

C ++ 100% 0ms code

- String으로 바꾸지 않고 맨 뒤의 값과 맨 앞의 값을 비교하면서 푼 코드

 class Solution {
public:
    bool isPalindrome(int x) {
        int temp = x;
        long rev, rem;
        rev = 0;
        
        if (x < 0)
            return false;
        
        while (temp != 0){
            rem = temp % 10;
            rev = rev * 10 + rem;
            temp = temp/10;
        }
        
        if (x == rev)
            return true;
        else
            return false;
    }
};

* 참고 링크 : https://kkminseok.github.io/posts/leetcode_Palindrome_Number/

 

 출처

 

https://leetcode.com/problems/palindrome-number/

 

반응형
2022-01-04 00:33:48
반응형

N개의 최소공배수

 

 문제 설명

 

두 수의 최소공배수(Least Common Multiple)란 입력된 두 수의 배수 중 공통이 되는 가장 작은 숫자를 의미합니다. 예를 들어 2와 7의 최소공배수는 14가 됩니다. 정의를 확장해서, n개의 수의 최소공배수는 n 개의 수들의 배수 중 공통이 되는 가장 작은 숫자가 됩니다. n개의 숫자를 담은 배열 arr이 입력되었을 때 이 수들의 최소공배수를 반환하는 함수, solution을 완성해 주세요.

 

 제한 사항

 

  • arr은 길이 1이상, 15이하인 배열입니다.
  • arr의 원소는 100 이하인 자연수입니다.

 

 입출력 예

 

arr return
[2, 6, 8, 14] 168
[1, 2, 3] 6

 

 Python 코드

 

import math

def solution(num):
    answer = num[0]
    for n in num:
        answer = (n * answer) // math.gcd(n, answer)
    return answer
  • 최대공약수 gcd는 math.gcd를 이용해 구해주고,
     
    최소공배수 lcm은 A * B // gcd(A,B) 이므로 for문을 돌면서 맨 마지막 answer를 return 해주면 된다.

* 참고 링크 : https://wookcode.tistory.com/101

def solution(arr):
    answer = 0
    max_num = 1
    for a in arr:
        max_num *= a
    
    for i in range(2, max_num+1):
        for a in arr:
            if i%a != 0:     # 나누어 떨어지지 않는다면 break
                break
                             # 위에서 break에 걸리지 않았다면 
                             # 모두 나누어 떨어지는 것이기 때문에 해당 i를 answer에 대입
        else:
            answer = i
            break
    return answer

* 참고 링크 : https://kimmeh1.tistory.com/190

 C++ 코드

 

#include <string>
#include <vector>

using namespace std;
int GCD(int a, int b){         // 최대공약수
    if(a == 0) return b;
    return GCD(b % a, a);
}
int LCM(int a, int b){         // 최소공배수
    return a * b / GCD(a,b);
}
int solution(vector<int> arr) {
    int answer = 0;
    answer = arr[0];
    for(int i=1;i<arr.size();i++){
        answer = LCM(answer, arr[i]);
    }
    return answer;
}
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int gcd(int x, int y) { return x % y == 0 ? y : gcd(y, x % y); }
int lcm(int x, int y) { return x * y / gcd(x, y); }
int solution(vector<int> arr) {
    int answer = arr[0];
    for (int i = 1; i < arr.size(); i++)
        answer = lcm(answer, arr[i]);
    return answer;
}

 

반응형
2022-01-04 00:18:12
반응형

문자열 다루기 기본

 

 문제 설명

 

문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. 예를 들어 s가 "a234"이면 False를 리턴하고 "1234"라면 True를 리턴하면 됩니다.

 

 제한 사항

 

  • s는 길이 1 이상, 길이 8 이하인 문자열입니다.

 

 입출력 예

 

s return
"a234" false
"1234" true

 

 Python 코드

 

def solution(s):

    if (len(s) == 4 or len(s) == 6) and s.isdigit():
        return True
    else:
        return False

 

* 참고 링크 : https://jeongchul.tistory.com/651

* isdigit ( ) 함수 : 문자열이 숫자로만 이루어져 있는지 확인하는 함수

- 문자가 단 하나라도 있다면 False를 반환하고, 모든 문자가 '숫자'로만 이루어져 있으면 True를 반환한다.

isdigit ( ) 함수는 string 클래스에 있는 메서드이다. 즉, 문자열.isdigit( ) 형태로 사용하는 메서드이다.

ex) str.isdigit()

a = "CodingTest" # 문자로만 이루어짐
b = "은하철도999" # 문자 + 숫자
c = "-999"       # 음수
d = "3.14"       # 소수점
e = "2022"       # 숫자

print(f"str.isdigit('{a}') : {str.isdigit(a)}")
print(f"str.isdigit('{b}') : {str.isdigit(b)}")
print(f"str.isdigit('{c}') : {str.isdigit(c)}")
print(f"str.isdigit('{d}') : {str.isdigit(d)}")
print(f"str.isdigit('{e}') : {str.isdigit(e)}")

print()

print(f"'{a}'.isdigit() : {a.isdigit()}")
print(f"'{b}'.isdigit() : {b.isdigit()}")
print(f"'{c}'.isdigit() : {c.isdigit()}")
print(f"'{d}'.isdigit() : {d.isdigit()}")
print(f"'{e}'.isdigit() : {e.isdigit()}")

 

 

* len() 함수 : 매개변수로 들어온 문자열의 길이를 반환

- 내부에 있는 문자의 갯수 및 공백을 포함한 카운팅을 하여 반환해주는 함수

- 문자열의 길이를 구할 때 용이

 
strlen = "HelloWorld"
 
print(len(strlen))
 
 
 
# 결과값 10

 

 C++ 코드

 

#include <string>
#include <vector>
//#include <cctype>
 
using namespace std;
 
bool solution(string s) 
{
    //1. 길이로 쳐낸다.
    const size_t length = s.length();
    if(length != 4 && length != 6)
    {
        return false;
    }
 
    //2. 문자가 있으면 쳐낸다.
    for(size_t i=0; i<length; ++i)
    {
        //if(!isdigit(s[i]))
        if(!(s[i] >= '0' && s[i] <= '9'))
        {
            return false;
        }
    }
 
    return true;
}

* 참고 링크 : https://blockdmask.tistory.com/280

반응형
2022-01-03 23:55:44
반응형

문자열 내림차순으로 배치하기

 

 문제 설명

 

문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요.
s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로 간주합니다.

 

 제한 사항

 

  • str은 길이 1 이상인 문자열입니다.

 

 입출력 예

 

s return
"Zbcdefg" "gfedcbZ"

 

 Python 코드

 

def solution(s):
    return "".join(sorted(list(s), reverse = True))

 

 

 

* join 함수 : 매개변수로 들어온 리스트에 있는 요소 하나하나를 합쳐서 하나의 문자열로 바꾸어 반환하는 함수


''.join(리스트)

'구분자'.join(리스트)

join 함수는 매개변수로 들어온 리스트에 있는 요소 하나하나를 합쳐서 하나의 문자열로 바꾸어 반환하는 함수이다.

- ''.join(리스트)
''.join(리스트)를 이용하면 매개변수로 들어온 ['a', 'b', 'c'] 이런 식의 리스트를 'abc'의 문자열로 합쳐서 반환해주는 함수이다.

- '구분자'.join(리스트)
'구분자'.join(리스트)를 이용하면 리스트의 값과 값 사이에 '구분자'에 들어온 구분자를 넣어서 하나의 문자열로 합쳐준다.
'_'.join(['a', 'b', 'c']) 라 하면 "a_b_c" 와 같은 형태로 문자열을 만들어서 반환해 준다.


''.join(리스트)는 '구분자'.join(리스트)에서 '구분자'가 그냥 공백인 것과 같다.

즉, 정리하자면 join함수의 찐 모양은 '구분자'.join(리스트) 이다.

참고 링크 : https://blockdmask.tistory.com/468

sorted(정렬할 데이터)

sorted(정렬할 데이터, reverse 파라미터) 

sorted(정렬할 데이터, key 파라미터)

sorted(정렬할 데이터, key 파라미터, reverse 파라미터)

※ 리스트의 메소드인 sort()를 사용하여도 정렬이 된다. 
이 경우에는 리스트 자체를 변경해 버린다. 
일반적으로 이것보다는 내장함수인 sorted()가 더 편리하다. 
또한 sort()는 리스트만을 위한 메소드이지만 sorted() 함수는 어떤 이터러블 객체도 받을 수 있다.

* 참고 링크 : https://blockdmask.tistory.com/466

 

* 리스트 정렬 (sort) : sort 함수는 리스트의 요소를 순서대로 정렬

a = [1, 4, 3, 2]
a.sort()
a
# result : [1, 2, 3, 4]
a = ['a', 'c', 'b']
a.sort()
a
# result : ['a', 'b', 'c']

 

* sorted ( ) 함수 : sorted(iterable) 함수는 입력값을 정렬한 후 그 결과를 리스트로 돌려주는 함수

sorted([3, 1, 2])
# result : [1, 2, 3]

sorted(['a', 'c', 'b'])
# result :  ['a', 'b', 'c']

sorted("zero")
# result :  ['e', 'o', 'r', 'z']

sorted((3, 2, 1))
# result : [1, 2, 3]

* 참고 링크 : https://wikidocs.net/32#sorted

 

 C++ 코드

 

#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
string solution(string s) {
    string answer = s;
    sort(answer.begin(),answer.end(),greater<char>());
    return answer;
}

https://wilybear.tistory.com/85

반응형
2022-01-03 22:24:23
반응형

문자열 내 p와 y의 개수

 

 문제 설명

 

대문자와 소문자가 섞여있는 문자열 s가 주어집니다. s에 'p'의 개수와 'y'의 개수를 비교해 같으면 True, 다르면 False를 return 하는 solution를 완성하세요. 'p', 'y' 모두 하나도 없는 경우는 항상 True를 리턴합니다. 단, 개수를 비교할 때 대문자와 소문자는 구별하지 않습니다.

예를 들어 s가 "pPoooyY"면 true를 return하고 "Pyy"라면 false를 return합니다.

 

 제한 사항

 

  • 문자열 s의 길이 : 50 이하의 자연수
  • 문자열 s는 알파벳으로만 이루어져 있습니다.

 

 입출력 예

 

s answer
"pPoooyY" true
"Pyy" false

 

 Python 코드

 

def solution(s):
    return s.lower().count('p') == s.lower().count('y')
  • lower ( ) 함수를 사용하여 문자열을 모두 소문자로 바꾼 뒤
  • count ( ) 함수로 문자열 내의 p와 y의 개수를 센 것 을 비교하여 바로 True 또는 False가 나옴

 

* upper ( ) 함수 : a를 대문자 문자열로 변환

* lower ( ) 함수 : b를 소문자 문자열로 변환

 
a = "hi"
 
print("a를 대문자로:", a.upper())
 
 
 
b = "HI"
 
print("b를 소문자로:", b.lower())

* count ( ) 함수 : 문자열에서 사용되는 함수로 특정 문자, 또는 문자열이 포함되어 있는지 카운팅 해주는 함수

 
 
 
str1 = '111112345'
print(str1.count('1')) #5
print(str1.count('11')) #2

my_name = 'minhee kang'
print(my_name.count('min')) #1
print(my_name.count('e'))  #2

# 리스트에 사용가능
my_name_list = ['min', 'hee', 'kang']
print(my_name_list.count('min')) #1
print(my_name_list.count('e'))  #0

# 튜플에 사용가능
my_name_tuple = ('min', 'hee', 1)  #이렇게 int 형 섞여있어도 가능
print(my_name_list.count('min')) #1
print(my_name_list.count('e'))  #0

# 집합에 사용가능
my_name_set = {'min', 'hee', 1}
print(my_name_list.count('min')) #1
print(my_name_list.count('e'))  #0
 
 

* 참고 링크 1 : https://wikidocs.net/13

* 참고 링크 2 : https://velog.io/@himinhee/python-count-%ED%95%A8%EC%88%98

 C++ 코드

 

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

char easytolower(char in) {
  if(in <= 'Z' && in >= 'A')
    return in - ('Z' - 'z');
  return in;
}

bool solution(string s)
{
    int p = 0;
    int y = 0;
    transform(s.begin(), s.end(), s.begin(), easytolower);
    for(int i = 0; i < s.size(); i++){
        if(s[i] == 'p')
            p++;
        else if(s[i] == 'y')
            y++;
    }

    if(p == y )
        return true;
    else
        return false;
}
#include <string>
#include <iostream>
using namespace std;
bool solution(string s)
{
	int p = 0, y = 0;
	for (int i = 0; i < s.length(); i++)
	{
		if (tolower(s[i]) == 'p') p++;
		else if (tolower(s[i]) == 'y') y++;
	}
	return (p - y == 0) ? true : false;
}

 

* 참고 링크 1 : https://jjeongil.tistory.com/603

* 참고 링크 2 : https://it-and-life.tistory.com/192

반응형