zoukankan      html  css  js  c++  java
  • 271. Encode and Decode Strings

        /*
         * 271. Encode and Decode Strings
         * 2016-6-25 by Mingyang
         * 这道题很酷的地方就是选择一种存储方式可以有效地存储string,我一开始就想到了存长度加string的方法
         * 这个题用了一个indexof的API,
         * public int indexOf(String str,int fromIndex)
         * Returns the index within this string of the first occurrence of the specified substring,
         * starting at the specified index.The returned index is the smallest value k for which:
         * k >= fromIndex && this.startsWith(str, k)
         * 就是说从fromIndex以后的第一次出现str的index
         */
          // Encodes a list of strings to a single string.
        public String encode(List<String> strs) {
            StringBuilder sb = new StringBuilder();
            for(String s : strs) {
                //这里加的/其实加任何符号都可以
                sb.append(s.length()).append('/').append(s);
            }
            return sb.toString();
        }
        // Decodes a single string to a list of strings.
        public List<String> decode(String s) {
            List<String> ret = new ArrayList<String>();
            int i = 0;
            while(i < s.length()) {
                int slash = s.indexOf('/', i);
                int size = Integer.valueOf(s.substring(i, slash));
                ret.add(s.substring(slash + 1, slash + size + 1));
                i = slash + size + 1;
            }
            return ret;
        }
  • 相关阅读:
    求树的某一层的节点最多
    快排 PAT 1101
    PAT 1098
    PAt 1099
    多项式求和
    pat 1100
    getline 函数
    数字的标准写法
    线性回归
    HTTP 中状态码 302的使用场景
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5617370.html
Copyright © 2011-2022 走看看