iT邦幫忙

2022 iThome 鐵人賽

DAY 27
0
自我挑戰組

JavaScript - 30天 - 自學挑戰系列 第 27

LeetCode Js-409. Longest Palindrome

  • 分享至 

  • xImage
  •  

LeetCode Js-409. Longest Palindrome

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

給予一個有大寫或小寫的字串 s,回傳可組成最長的字串。
(ex.
    左右對稱:noon 
    中心對稱:radar, level)

Example 1:

Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Solution:

  1. 設定 counts 為 Object literals {}。
  2. 宣告符合字串的長度為 0,條件為 false(如為中心對稱則需 + 1)。
  3. 將 counts 中依序放入物件與對應個數。
  4. 將每一個 counts 中的字母個數,進行 2 的餘數計算:
- 剩餘 0: 長度加上此字母的個數
- 不剩餘 0: 長度加上此字母的個數 - 1 (此數中心點,故須 - 1)
         且符合中心對稱條件。
  1. 如果 condition 設定的條件為:
- condition = true: 長度 + 1
- condition = false: 長度維持不變
  1. 回傳長度。

Code:

var longestPalindrome = function(s) {
  const counts = {}
  let length = 0, condition = false

  for (let i = 0; i < s.length; i++) {
    counts[s[i]] = (counts[s[i]] || 0) + 1
  }
  
  for (let letter in counts) {
    if (counts[letter] % 2 === 0) {
      length += counts[letter]
    } else {
      condition = true
      length += counts[letter] - 1
    }
  }
  if (condition) {length += 1}

  return length
}

FlowChart:
Example 1

Input: s = "abccccdd"
length = 0, condition = false
counts = {a: 1}
counts = {a: 1, b: 1}
counts = {a: 1, b: 1, c: 1}
counts = {a: 1, b: 1, c: 2}
counts = {a: 1, b: 1, c: 3}
counts = {a: 1, b: 1, c: 4}
counts = {a: 1, b: 1, c: 2, d: 1}
counts = {a: 1, b: 1, c: 4, d: 2}

step.1
counts[letter] % 2 = 1 //{ a: 1}, 1 % 2 = 1
condition = true
length += counts[letter] - 1 //0 + 1 - 1 = 0

step.2
counts[letter] % 2 = 1 //{ b: 1}, 1 % 2 = 1
condition = true
length += counts[letter] - 1 //0 + 1 - 1 = 0

step.3
counts[letter] % 2 = 0 //{ c: 4}, 4 % 2 = 0
condition = true
length += counts[letter] //0 + 4 = 4

step.4
counts[letter] % 2 = 0 //{ d: 2}, 2 % 2 = 0
condition = true
length += counts[letter] //4 + 2 = 6

step.5
condition = true => length += 1 = 6 + 1 = 7 
(ex.符合中心對稱,故對稱的長度再加上中心點。

return length //7

上一篇
LeetCode Js-724. Find Pivot Index
下一篇
LeetCode Js-53. Maximum Subarray
系列文
JavaScript - 30天 - 自學挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言