New Leetcode Track[Easy]

深藏阁楼爱情的钟 2022-09-10 02:17 284阅读 0赞

I am a new research guy with a hard time in reading papers.
So there has little time for me to coding.
In order to master Python and keep coding, I try leetcode again.
I am trainning my English, so this blog wouldn’t show any Chinese.
Let’s begin and pythonic, it’s hard to start with everything.

9.3 7. Reverse Integer

First post a very amazing version, it’s really awsome!!!

  1. def reverse(self, x):
  2. s=cmp(x,0);r=int(`s*x`[::-1]);return(r<2**31)*s*r

This is my first version. Because forgot the rule of leetcode, I used print rather than return.

  1. flag, stack, tail = True, [], -1
  2. if x < 0: flag, x = False, -x
  3. while x > 0:
  4. stack.append(x % 10)
  5. tail += 1
  6. x //= 10
  7. if flag is False:
  8. print("-", end="")
  9. if tail == -1:
  10. print("0", end="")
  11. for i in range(0, tail+1):
  12. print(stack[i], end="")
  13. print("")

I try how to print without new line in Python.

  1. print("", end="")

This is my final version, please check the Description

If reversing x x x causes the value to go outside the signed 32-bit integer range [ − 2 31 , 2 31 − 1 ] [-2^{31}, 2^{31} - 1] [−231,231−1], then return 0 0 0.

  1. class Solution:
  2. def reverse(self, x: int) -> int:
  3. flag, stack, tail = True, [], -1
  4. if x < 0: flag, x = False, -x
  5. while x > 0:
  6. stack.append(x % 10)
  7. tail += 1
  8. x //= 10
  9. ans, mul = 0, 1
  10. for i in reversed(stack):
  11. ans += i*mul
  12. mul *= 10
  13. ans = 0 if abs(ans) > (2**31) else ans
  14. return ans if flag else -ans
9.9 9. Palindrome Number

long time not to code ACM problem
When I watch the describition, I always want to use a data struction figuring out the problem.
But I forgot it is a simple level question. Please let me be simple.

  1. class Solution:
  2. def isPalindrome(self, x: int) -> bool:
  3. if x < 0: return False
  4. origin, reverse = x, 0
  5. while x > 0:
  6. reverse = reverse * 10 + (x % 10)
  7. x = x // 10
  8. return origin == reverse

And there is a pythonic version:

  1. class Solution:
  2. def isPalindrome(self, x: int) -> bool:
  3. if x<2**31-1 and x>-2**31 :
  4. if str(x) == str(x)[::-1]:
  5. return 1
  6. else:
  7. return 0
  8. else:
  9. return 0

reverse the string and determine equality

9.9 13. Roman to Integer

When I watch the Roman number, I want to use the map, but when I am coding I decided to use string directly. So my code is long.

  1. class Solution:
  2. def romanToInt(self, s: str) -> int:
  3. n = len(s)
  4. roman = { 'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
  5. # for i, symbol in enumerate(s[::-1]):
  6. tail, ans = n - 1, 0
  7. while(tail > -1):
  8. if s[tail] == 'I':
  9. ans += 1
  10. tail -= 1
  11. if s[tail] == 'V' or s[tail] == 'X':
  12. temp = 5 if s[tail] == 'V' else 10
  13. while(tail > 0 and s[tail-1] == 'I'):
  14. temp -= 1
  15. tail -= 1
  16. ans += temp
  17. tail -= 1
  18. if s[tail] == 'L' or s[tail] == 'C':
  19. temp = 50 if s[tail] == 'L' else 100
  20. while(tail > 0 and s[tail-1] == 'X'):
  21. temp -= 10
  22. tail -= 1
  23. ans += temp
  24. tail -= 1
  25. if s[tail] == 'D' or s[tail] == 'M':
  26. temp = 500 if s[tail] == 'D' else 1000
  27. while(tail > 0 and s[tail-1] == 'C'):
  28. temp -= 100
  29. tail -= 1
  30. ans += temp
  31. tail -= 1
  32. pass
  33. return ans

The fastest version in leetcode submissions. Record the previous char is a useful method.

  1. class Solution:
  2. def romanToInt(self, s: str) -> int:
  3. convert = { 'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X' : 10, 'V': 5, 'I': 1}
  4. prevChar = 'I'
  5. answer = 0
  6. for char in s[::-1]:
  7. if convert[char] >= convert[prevChar]:
  8. answer += convert[char]
  9. prevChar = char
  10. else:
  11. answer -= convert[char]
  12. return answer

9.13 14. Longest Common Prefix

Note the boundary conditions!!!

  1. class Solution:
  2. def longestCommonPrefix(self, strs: List[str]) -> str:
  3. # n = len(strs)
  4. if len(strs) == 1: return strs[0]
  5. minn = 1e7
  6. for i in strs:
  7. minn = min(len(i),minn)
  8. ans = ""
  9. for i in range(minn):
  10. now = strs[0][:i+1]
  11. flag = 1
  12. for s in strs:
  13. if now != s[:i+1]:
  14. flag = 0
  15. break
  16. if flag == 1:
  17. ans = now
  18. else: break
  19. return ans

The fastest version, use the set to count the number of the different alpha in the same position. If the number equal one, the alpha is the same.

  1. class Solution:
  2. def longestCommonPrefix(self, strs: List[str]) -> str:
  3. minLength = min([len(s) for s in strs])
  4. prefix = ''
  5. for n in range(minLength):
  6. c = list(set([strs[i][n] for i in range(len(strs))]))
  7. if len(c) == 1:
  8. prefix += c[0]
  9. else:
  10. break
  11. return(prefix)

9.14 20. Valid Parentheses

stack please think twice before submit

  1. class Solution:
  2. def isValid(self, s: str) -> bool:
  3. stack, tail = [], -1
  4. for c in s:
  5. if tail == -1:
  6. stack.append(c)
  7. tail += 1
  8. elif stack[tail] == '(' and c == ')':
  9. stack = stack[:tail]
  10. tail -= 1
  11. elif stack[tail] == '{' and c == '}':
  12. stack = stack[:tail]
  13. tail -= 1
  14. elif stack[tail] == '[' and c == ']':
  15. stack = stack[:tail]
  16. tail -= 1
  17. elif c == '(' or c == '{' or c == '[':
  18. stack.append(c)
  19. tail += 1
  20. else: return False
  21. return True if tail == -1 else False

The fastest version:

  1. class Solution:
  2. def isValid(self, s: str) -> bool:
  3. stack = []
  4. for i in s:
  5. if i in ['[' , '{' , '('] :
  6. stack.append(i)
  7. elif stack :
  8. if i == ']' and stack[-1] == '[':
  9. stack.pop()
  10. elif i == ')' and stack[-1] == '(':
  11. stack.pop()
  12. elif i == '}' and stack[-1] == '{':
  13. stack.pop()
  14. else:
  15. return False
  16. else:
  17. return False
  18. if stack:
  19. return False
  20. else:
  21. return True

so list can pop() and can use

  1. if i in ['[', '{', '(']:

to judge

发表评论

表情:
评论列表 (有 0 条评论,284人围观)

还没有评论,来说两句吧...

相关阅读

    相关 New Year, New Me

    新的一年,新的开始 2017年,是我的毕业年,也是我开始参加工作的一年,这一年,很忙碌,很充实,却也很累,但也在一一实现着17年的计划,直到今日,十之八九得到了一个圆满的