/* * 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; }
时间: 2024-10-14 08:52:54