Evaluate Reverse Polish Notation

 

 문제 설명

 

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

* 역폴란드 표기법 : https://ko.wikipedia.org/wiki/역폴란드_표기법

 제한 사항

 

  • 1 <= tokens.length <= 104
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].

 

 입출력 예

 

Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

 

Example 3:

Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

 

 Python 코드

 

Python code 

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for t in tokens:
            if t not in {"+", "-", "*", "/"}:
                stack.append(int(t))
            else:
                b, a = stack.pop(), stack.pop()
                if t == "+": stack.append(a + b)
                elif t == "-": stack.append(a - b)
                elif t == "*": stack.append(a * b)
                else: stack.append(trunc(a / b))
        return stack[0]

* 참고 링크 : https://dev.to/seanpgallivan/solution-evaluate-reverse-polish-notation-192l

* 설명 참고 링크 : https://www.youtube.com/watch?v=P8xYysvjLd0 

 

 C++ 코드

 

C ++ code

int evalRPN(vector<string>& tokens)
{
    stack<int>st;
    for(auto it : tokens)
    {
        if(it=="+" || it=="-" || it=="*" || it=="/"  )
        {
            int f = st.top();st.pop();
            int s = st.top();st.pop();

            if (it == "+")
              { int r = s + f;  st.push(r); }
            else if (it == "*")
              { int r = s * f;  st.push(r); }
            else if (it == "-")
              { int r = s - f;   st.push(r); }
            else if (it == "/")
              { int r = s / f;   st.push(r); }
        }
        else{ st.push( stoi(it)); }
    }
    return st.top();
}

* 참고 링크 : https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1234191/c-easy-optimized-solution-150-evaluate-reverse-polish-notation

 

 출처

 

https://leetcode.com/problems/evaluate-reverse-polish-notation/

43. Multiply Strings

 

 문제 설명

 

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

 제한 사항

 

  • 1 <= num1.length, num2.length <= 200
  • num1 and num2 consist of digits only.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.

 

 입출력 예

 

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

 

 Python 코드

 

Python code 

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        def str_to_int(num_str):
            num = 0
            for i, c in enumerate(num_str[::-1]):
                num += pow(10, i) * (ord(c) - ord('0'))
            return num

        return str(str_to_int(num1) * str_to_int(num2))

* 참고 링크 : https://wellsw.tistory.com/94?category=1054641

 

 C++ 코드

 

C ++ code

class Solution {
public:
	string multiply(string num1, string num2) {
		string res(num1.size() + num2.size(), '0');
		for (int i = num1.size() - 1; i >= 0; --i) {
			int carry = 0;
			for (int j = num2.size() - 1; j >= 0; --j) {
				int tmp = (res[i + j + 1] - '0') + (num2[j] - '0')*(num1[i] - '0') + carry;
				res[i + j + 1] = tmp % 10 + '0';
				carry = tmp/10;
			}
			res[i] += carry;
		}
		auto pos = res.find_first_not_of('0');
		if (pos == string::npos)
			return "0";
		return res.substr(pos, res.length() - pos);
	}
};

* 참고 링크 : https://blog.fearcat.in/a?ID=00850-66ef66e8-11ca-463c-82ae-c4af5cb77fae

 

 출처

 

https://leetcode.com/problems/multiply-strings/

Remove Element

 

 문제 설명

 

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
                            // It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
    assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted.

 제한 사항

 

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

 

 입출력 예

 

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

 

 Python 코드

 

Python code 

class Solution: 
    def removeElement(self, nums: List[int], val: int) -> int:
        answer = [num for num in nums if num != val] 
        for i in range(len(answer)): 
            nums[i] = answer[i] 
            
        nums = nums[:len(answer)] 
        return len(nums)

 

* 참고 링크 : https://somjang.tistory.com/entry/leetCode-27-Remove-Element-Python

https://redquark.org/leetcode/0027-remove-element/

class Solution:
    def removeElement(self, nums, val):
        for i in range(len(nums)):
            if nums[0] != val:
                nums.append(nums[0])
                del nums[0]
            else:
                del nums[0]
        return len(nums)

* 참고 링크 : https://bortfolio.tistory.com/124

 C++ 코드

 

C ++ code

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int count = 0;
        for(int i = 0; i < nums.size(); i++){
            if (nums[i] != val){
                nums[count++] = nums[i];
            }
        }
        return count;
    }
};

* 참고 링크 : https://egbert-yu-ting.github.io/posts/1afffcb4/

https://lessbutbetter.tistory.com/entry/LeetCodeEasyC%EB%AC%B8%EC%A0%9C%ED%92%80%EC%9D%B4-27-Remove-Element

 출처

 

https://leetcode.com/problems/remove-element/

Valid Parentheses

 

 문제 설명

 

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

 

 제한 사항

 

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

 

 입출력 예

 

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

 

 

 Python 코드

 

Python code 

class Solution:
  def isValid(self, s: str) -> bool:
      stack = []
      dic = {'(':')',
             '{':'}',
             '[':']'
            }

      for char in s:
          if char in dic.keys():
              stack.append(char)

          elif stack == [] or char != dic[stack.pop()] :
              return False

      return stack ==[]

 

* 참고 링크 : https://chaerim-kim.github.io/data%20structures%20and%20algorithms/ValidParentheses/

class Solution:
    def isValid(self, s: str) -> bool:
        stack=[]
        brackets={'}':'{',')':'(',']':'['}
        for bracket in s:
            if bracket in brackets.values(): #Opening bracket 
                stack.append(bracket)
            else:# Closing bracket
                if stack and brackets[bracket]==stack[-1] :  
                    stack.pop()
                else: 
                    return False
        
        if stack:
            return False
        return True

* 참고 링크 : https://velog.io/@kgh732/Python-%EC%9C%BC%EB%A1%9C-%ED%91%B8%EB%8A%94-Leetcode20.-Valid-Parentheses

class Solution: 
	def isValid(self, s: str) -> bool: 
    	s_list = list(s)
        
        answer = True 
        
        stack = [] 
        
        for s in s_list: 
        	if s == '[' or s == '(' or s == '{': 
            	stack.append(s) 
            elif len(stack) != 0: 
            	if (s == ']' and stack[-1] == '[') or (s == '}' and stack[-1] == '{') or (s == ')' and stack[-1] == '('): 
                	stack.pop() 
                else: 
                    answer = False 
                    break 
            else: 
            	answer = False 
                break 
                
        if len(stack) != 0: 
        	answer = False 
        return answer

* 참고 링크 : https://somjang.tistory.com/entry/leetCode-20-Valid-Parentheses-Python

 

C++ 코드

 

C ++ code

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        
        for(int i = 0; i < s.size(); i++) {
            if(s.at(i) == '{' || s.at(i) == '(' || s.at(i) == '[')      st.push(s.at(i));
            else {
                if(st.empty())      return false;
                else {
                    if((s.at(i) == '}' && st.top() != '{') || (s.at(i) == ')' && st.top() != '(') 
                        || (s.at(i) == ']' && st.top() != '['))
                            st.push(s.at(i));
                    else    st.pop();
                }
            }   
        }
        
        return st.empty();
    }
};

* 참고 링크 : https://m.blog.naver.com/tac1994/221839649888

 

 출처

 

https://leetcode.com/problems/valid-parentheses/submissions/

Palindrome Linked List

 

 문제 설명

 

Given the head of a singly linked list, return true if it is a palindrome.

 

 제한 사항

 

  • The number of nodes in the list is in the range [1, 105].
  • 0 <= Node.val <= 9

 

 입출력 예

 

Example 1:

Input: head = [1,2,2,1]
Output: true

 

Example 2:

Input: head = [1,2]
Output: false

 

 Python 코드

 

Python code 

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        val_list = []
        curr = head
        while curr:
            val_list.append(curr.val)
            curr = curr.next
        return val_list == val_list[::-1]

 

* 참고 링크 : https://ceuity.tistory.com/12

https://velog.io/@jayb/LeetCode-234.Palindrome-Linked-List%ED%8C%B0%EB%A6%B0%EB%93%9C%EB%A1%AC-%EC%97%B0%EA%B2%B0-%EB%A6%AC%EC%8A%A4%ED%8A%B8

 C++ 코드

 

C ++  code

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *slow = head, *fast = head, *prev, *temp;
        while (fast && fast->next)
            slow = slow->next, fast = fast->next->next;
        prev = slow, slow = slow->next, prev->next = NULL;
        while (slow)
            temp = slow->next, slow->next = prev, prev = slow, slow = temp;
        fast = head, slow = prev;
        while (slow)
            if (fast->val != slow->val) return false;
            else fast = fast->next, slow = slow->next;
        return true;
    }
};

 

* 참고 링크 : https://dev.to/seanpgallivan/solution-palindrome-linked-list-5721

 

 출처

 

https://leetcode.com/problems/palindrome-linked-list/submissions/

Single Number

 

 문제 설명

 

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

 

 제한 사항

 

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

 

 입출력 예

 

Example 1:

Input: nums = [2,2,1]
Output: 1

Example 2:

Input: nums = [4,1,2,1,2]
Output: 4

Example 3:

Input: nums = [1]
Output: 1

 

 Python 코드

 

Python code 

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        answer = 0
        for i in nums:
            answer = answer ^ i
        return answer
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        cnt_dict = Counter(nums) 
        items = cnt_dict.items()
        
        for key, val in items:
            if val == 1:
                answer = key
                break
                
        return answer

* 참고 링크 : https://airsbigdata.tistory.com/89

 

 C++ 코드

 

C ++ 100% 0ms code

nt singleNumber(int a[], int n) {
     //xor all numbers, the left over number would be the non repeated one
     // since the equl numbers cancel out each others bits
     int num = 0;
     for (int i = 0; i < n; ++i) {
         num ^= a[i];
     }
     return num;
    }

* 참고 링크 : https://leetcode.com/problems/single-number/discuss/43237/4-lines-of-c%2B%2B-solution

 

 출처

 

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

Pascal's Triangle

 

 문제 설명

 

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

 

 제한 사항

 

  • 1 <= numRows <= 30

 

 입출력 예

 

Example 1:

Input : numRows = 5
Output : [[1], [1.1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]

Example 2:

Input : numRows = 1
Output : [[1]]

 

 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)
  •  

* 참고 링크 : 

 

 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/pascals-triangle/

3Sum

 

 문제 설명

 

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

 

 제한 사항

 

  • 0 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

 

 입출력 예

Example 1:

Input : num = [-1, 0, 1, 2, -1, -4]
Output : [[-1, -1, 2], [-1, 0, 1]]

Example 2:

Input : nums = []
Output : []

Example 3:

Input : nums = [0]
Output : []

 

 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)
  •  

* 참고 링크 : 

 

 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/3sum/

 

Add Two Numbers

 

 문제 설명

 

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

 

 제한 사항

 

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

 

 입출력 예

 

Example 1:

Input : l1 = [2, 4, 3], l2 = [5, 6, 4]
Output : [7, 0, 8]
Explanation : 342 + 465 = 807

Example 2:

Input : l1 = [0], l2 = [0]
Output : [0]

Example 3:

Input : l1 = [9, 9, 9, 9, 9, 9, 9], l2 = [9, 9, 9, 9]
Output : [8, 9, 9, 9, 0, 0, 0, 1]

 

 Python 코드

 

Python 8ms code 

dd
  •  

* 참고 링크 : 

 

 C++ 코드

 

C ++ 100% 0ms code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

* 참고 링크 : 

 

 출처

 

https://leetcode.com/problems/add-two-numbers/

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/

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/

 

+ Recent posts