Implement Queue using Stacks

 

 문제 설명

 

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

Notes:

  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

 

 제한 사항

 

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, peek, and empty.
  • All the calls to pop and peek are valid.

 

 입출력 예

 

Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

 

 Python 코드

 

Python code 

class MyQueue: 
	def __init__(self): 
		// 문제에서 2개의 스택을 사용하라고 하니, 배열을 2개를 사용
		self.stack1 = [] 
		self.stack2 = [] 
		
	def push(self, x: int): 
		// stack1에는 push 데이터를 넣어줌
		self.stack1.append(x) 
		
	def pop(self): 
	// pop을 할때에는 stack1의 배열을 거꾸로 변경하는 과정이 필요
	// pop을 할때, stack1.pop()을 하여, stack2에 넣어줌
	// stack1 [1, 2, 3] -> stack2 = [3, 2, 1] 
		self.peek() 
		return self.stack2.pop() 
		
	def peek(self): 
		// peek는 큐의 첫번째 값을 가져와야 하므로 
		// stack1의 모든 값을 거꾸로 stack2에 넣어서, stack2[-1]을 리턴
		
		if not self.stack2: 
		// stack1의 모든 값이 나올때까지 해주는데, 
		// stack2가 비어있지 않은 경우에 stack2에 값을 넣을 경우 
		// pop()이 힘들어지니 stack1을 그대로 이용
		
		// 1) stack1 [1, 2, 3] -> stack2 [3, 2, 1] 
		// 2) MyQueue.push(4) 
		// 3) stack1 -> [4] , stack2 [3, 2, 1] 의 경우 
		// stack1의 값을 넣어주면 stack2는, [3, 2, 1, 4]가 되므로 pop을 하기가 힘듬 
		// 4) stack1의 [4]는 어차피 stack2가 다 빌때까지 필요없으므로 
		// 그냥 stack2가 빌때까지 stack1에 넣어둠 
		
			while self.stack1: 
				self.stack2.append(self.stack1.pop()) 
		return self.stack2[-1] 
		
		
	def empty(self): 
		return (len(self.stack1) == 0) and (len(self.stack2) == 0)

* 참고 링크 : https://jasmine46.tistory.com/71

 

 C++ 코드

 

C ++ code

// Time:  O(1), amortized
// Space: O(n)

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        A_.emplace(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        peek();
        B_.pop();
    }

    // Get the front element.
    int peek(void) {
        if (B_.empty()) {
          // Transfers the elements in A_ to B_.
          while (!A_.empty()) {
            B_.emplace(A_.top());
            A_.pop();
          }
        }
        if (B_.empty()) {  // B_ is still empty!
          throw length_error("empty queue");
        }
        return B_.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return A_.empty() && B_.empty();
    }

 private:
  stack<int> A_, B_;
};

* 참고 링크 : https://shareablecode.com/snippets/implement-queue-using-stacks-c-solution-leetcode-FaBa-R43B

 

 출처

 

https://leetcode.com/problems/implement-queue-using-stacks/

Implement Stack using Queues

 

 문제 설명

 

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

  • void push(int x) Pushes element x to the top of the stack.
  • int pop() Removes the element on the top of the stack and returns it.
  • int top() Returns the element on the top of the stack.
  • boolean empty() Returns true if the stack is empty, false otherwise.

Notes:

  • You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
  • Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.

 

 제한 사항

 

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, top, and empty.
  • All the calls to pop and top are valid.

 

 입출력 예

 

Example 1:

Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

 Python 코드

 

Python code 

class MyStack:

    def __init__(self):
        self.q = deque()

    def push(self, x: int) -> None:
        self.q.append(x)

    def pop(self) -> int:
        for i in range(len(self.q) - 1):
            self.push(self.q.popleft())
        return self.q.popleft()

    def top(self) -> int:
        return self.q[-1]

    def empty(self) -> bool:
        return len(self.q) == 0

# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

* 참고 링크 : https://www.youtube.com/watch?v=rW4vm0-DLYc 

 

 C++ 코드

 

C ++ code

class MyStack {
    queue<int>q;
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) 
    {
        q.push(x);
        for (int i=0; i<q.size()-1; i++)
        {
            q.push(q.front());
            q.pop();
        }        
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() 
    {
        int result=q.front();
        q.pop();
        return result;
    }
    
    /** Get the top element. */
    int top() 
    {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() 
    {
        return q.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * bool param_4 = obj.empty();
 */

* 참고 링크 : https://github.com/wisdompeak/LeetCode/blob/master/Stack/225.Implement-Stack-using-Queues/225.Implement%20Stack%20using%20Queues.cpp

 

 출처

 

https://leetcode.com/problems/implement-stack-using-queues/submissions/

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/

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