[Neetcode] Encode and Decode Strings

whitehousechef·2025년 8월 20일

https://neetcode.io/problems/string-encode-and-decode?list=neetcode150

initial

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

sol

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;
    }
}

complexity

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

0개의 댓글