https://neetcode.io/problems/string-encode-and-decode?list=neetcode150
i thought maybe using a separator like dash but dash is considerd utf-8, which question said could be given as a string so i cannot use.
the encoding format should be "length#string" like "4#hola". Once we see the #, we substring the previous index as length and substring that much of length to get the original string
clever and clean way to impl this
class Solution {
public String encode(List<String> strs) {
String tmp = "";
for(String word: strs){
int length = word.length();
tmp += String.valueOf(length)+"#"+word;
}
System.out.println(tmp);
return tmp;
}
public List<String> decode(String str) {
List<String> ans = new ArrayList<>();
int idx=0;
while(idx<str.length()){
int j = idx;
while(str.charAt(j)!='#')j+=1;
int length = Integer.valueOf(str.substring(idx,j));
String cur_string = str.substring(j+1,j+length+1);
ans.add(cur_string);
idx=j+length+1;
}
return ans;
}
}
n time n space NOOOOOOOOOO its actually k^2 time
not n time cuz im making new string each time i do string += like this way
I organised that time here https://velog.io/@whitehousechef/Time-and-Space-Calc
so if i use sb, its k time and space