Pages

Wednesday, February 18, 2026

Encode and Decode Strings - NeetCode.IO Solution by me + gemini pro 3.0 explained

 class Solution {

        // encode: List of Strings -> String
    public String encode(List<String> strs) {
        StringBuilder sb = new StringBuilder();

        for(String str : strs) {
            // Pattern: Length + Delimiter # + String
            sb.append(str.length()).append("#").append(str);
        }


        return sb.toString(); // return in String
    }


        // decode: String -> List of Strings
    public List<String> decode(String str) {
        List<String> res = new ArrayList<>(); // store res
        int i = 0; // var. for loop

        while(i < str.length()) {
            // 1. find delimitter to get length prefix
            int slash = str.indexOf('#', i);

            // 2. parse the length from characters between i and slash
            int length = Integer.parseInt(str.substring(i, slash));

            // 3. store extractedStr
            String extString = str.substring(slash + 1, slash + 1 + length);
            res.add(extString);

            // 4. move the pointer 'i' to the start of next encoded_String
            i = slash + 1 + length;
        }

        return res;
    }
}

No comments:

Post a Comment

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...