Encode and Decode Strings
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Please implement encode
and decode
Example
Example1
Input: ["lint","code","love","you"] Output: ["lint","code","love","you"] Explanation: One possible encode method is: "lint:;code:;love:;you"
Example2
Input: ["we", "say", ":", "yes"] Output: ["we", "say", ":", "yes"] Explanation: One possible encode method is: "we:;say:;:::;yes"
Solution :
class Solution:def encode(self, strs):ans = " "for s in strs:ans += str(len(s)) + "$" + sreturn ansdef decode(self, str):ans = []i = 0while i < len(str):j = iwhile str[j] != "$":j += 1l = int(str[i:j])ans.append(str[j+1:j+1+l])i = j + 1 + lreturn ans
Explaination :
Comments
Post a Comment