Not using the length() of string to do separation. Mimic the way of escape Character like '\'.


  • 0

    import java.util.*;

    public class Codec {

    // Encodes a list of strings to a single string.
    private String transfer(String str)
    {
        String res = "";
        
        for(int i=0; i<str.length(); i++)
        {
            if(str.charAt(i) == '%' || str.charAt(i) == '/')
            {
                res = res + '/' + str.charAt(i);
            }
            else
                res += str.charAt(i);
        }
        
        return res;
    }
    
    public String encode(List<String> strs) {
       String res = "";
       
       for(String s : strs)
       {
           res = res + "%" + transfer(s);
       }
       
       return res;
    }
    
    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
       List<String> list = new ArrayList<String>();
       
       if(s.length() == 0)
        return list;
      
       int i = 1;
       boolean flag = false;
       StringBuffer sb = new StringBuffer();
       
       while(i < s.length())
       {
          char ch = s.charAt(i);
          if(flag == true)
          {
              sb.append(ch);
              flag = false;
          }
          else if(ch == '/')
          {
              flag = true;
          }
          else if(ch == '%')
          {
              list.add(sb.toString());
              sb = new StringBuffer();
          }
          else
            sb.append(ch);
          
          i++;
       }
       
       list.add(sb.toString());
       
       return list;
    }
    

    }

    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.decode(codec.encode(strs));


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.