Problem 271: Encode and Decode Strings
Last updated
Was this helpful?
Last updated
Was this helpful?
我们可以维护一个 StringBuilder,读出每个 input string 的长度,append 一个特殊字符,例如 '/',再 append string。
decode 的时候我们就可以利用 java 的 String.indexOf(char,startIndex)来算出自 startIndex 其第一个 '/' 的位置,同时计算出接下来读取的 string 长度,用 String.substring() 读出字符串以后我们更新 index,来进行下一次读取。
Time: O(n)
Space: O(1)
String.indexOf() 方法
这里 index,充当的是“起始位置”,也就是说,从这个位置开始以后看有没有 "/"
substring() 方法中,是“左闭右开”区间,注意不要搞错