給一組有效的 IPv4 的 IP 地址,返回該 IP 地址的默認版本。
然後這個違規的 IP 地址會將句號 "." 用 "[.]" 取代。
LeetCode eetCode 題目連結
https://leetcode.com/problems/defanging-an-ip-address/
題目
1108. Defanging an IP Address
Easy
Given a valid (IPv4) IP
address
, return a defanged version of that IP address.
A defanged IP address replaces every period
"."
with "[.]"
.
Example 1:
Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0"
Constraints:
- The given
address
is a valid IPv4 address.
Accept 作法
Runtime: 188 ms
Memory: 36.6 mb
class Solution { fun defangIPaddr(address: String): String { val result = address.replace(".","[.]") return result } }
後來選擇還是不要套現成的 API 好了。就有第二種作法。
Runtime: 140 ms
Memory: 31.6 mb
Kotlin
class Solution { fun defangIPaddr(address: String): String { var newAddress = ""; for(i in 0..address.length-1){ if(address.get(i).toString().equals(".")){ newAddress = newAddress+"["+ address.get(i)+"]" }else{ newAddress = newAddress+address.get(i) } } return newAddress } }
這邊 Kotlin 跟 Java 的 String 不一樣的是它拿每一個字元直接用 get 不是 charAt , get 回來轉型成 String 才能用 equals 來比對。
還有第三種作法,String 最常被討論如果有大量字串處理時有效能問題,用 StringBuilder 比較好,於是這題就拿來實驗看看,但結果時間一樣,我想是因為本身字串長度就滿短的,所以沒差。
Runtime: 140 ms
Memory: 31.6 mb
Kotlin
class Solution { fun defangIPaddr(address: String): String { var newAddress = StringBuilder(); for(i in 0..address.length-1){ if(address.get(i).toString().equals(".")){ newAddress.append("["+ address.get(i)+"]") }else{ newAddress.append(address.get(i)) } } return newAddress.toString() } }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
It come to be an appealing part of a blog whilst author uses oblique speech even as writing a blog. It suggests your creative thoughts as well as make your written essay specific from others. kickass proxy
回覆刪除written content. I added new knowledge to my database for essay writing skill. text to image
回覆刪除