Encode & Decode
最近被各种 encode 和 decode 算法虐得很晕,总结一下,但愿有通解??
No.1 Compress a string to remove duplicates when a character occurs +2 times continuously.
e.g.
input : "12 abbbbbbbbbbbbbbc 3aaaa12bbxxx2 hello"
output: "12 a14xbc 1x34xa12bb3xx2 hello".
分析 Corner Case
* 1. number + repeat character : 3aaaaa -> 1x35xa
* 2. "number"+"x"+"character" already exist in original string : 3xa -> 1x31xxa
1 public class CompressString { 2 public static void main(String[] args) { 3 // String str = "12 abbbbbbbbbbbbbbc 3aaaa12bb3x223444 hello"; 4 String str = "123456c2xc"; 5 if (str == null || str.length() == 0) 6 return; 7 StringBuilder output = new StringBuilder(); 8 output.append(""); 9 int i = str.length()-1, j = str.length()-1; 10 int cur_num = 0; 11 boolean prex = false; 12 char cur = str.charAt(j); 13 while (i >= 0) { 14 if (str.charAt(i) == cur) { 15 i--; 16 } else { 17 cur_num = j - i; 18 if (cur >= ‘0‘ && cur <=‘9‘) { 19 if (!prex && cur_num <= 2) { 20 int c = 0; 21 while (c < cur_num) { 22 output.insert(0, cur); 23 c++; 24 } 25 prex = false; 26 } else { 27 output.insert(0, cur); 28 output.insert(0, ‘x‘); 29 output.insert(0, cur_num); 30 prex = true; 31 } 32 } else if (cur_num <= 2 && cur!=‘x‘) { 33 int c = 0; 34 while (c < cur_num) { 35 output.insert(0, cur); 36 c++; 37 } 38 prex = false; 39 } else { 40 output.insert(0, cur); 41 output.insert(0, ‘x‘); 42 output.insert(0, cur_num); 43 prex = true; 44 } 45 cur = str.charAt(i); 46 j = i; 47 i--; 48 } 49 } 50 cur_num = j - i; 51 if (cur >= ‘0‘ && cur <=‘9‘) { 52 if (!prex && cur_num <= 2) { 53 int c = 0; 54 while (c < cur_num) { 55 output.insert(0, cur); 56 c++; 57 } 58 } else { 59 output.insert(0, cur); 60 output.insert(0, ‘x‘); 61 output.insert(0, cur_num); 62 } 63 } else if (cur_num <= 2) { 64 int c = 0; 65 while (c < cur_num) { 66 output.insert(0, cur); 67 c++; 68 } 69 } else { 70 output.insert(0, cur); 71 output.insert(0, ‘x‘); 72 output.insert(0, cur_num); 73 } 74 System.out.println(output.toString()); 75 } 76 }
No.2 There is a decode method F, which could
F ("someString" + "x" + "anyNumber") --> "someString""someString"..."someString" (n times of such a string)
e.g.
aaax -> ax3x
分析 Corner Case
* 1. repeat string + number : aaa3 -> ax2a3
* 2. "string"+"x"+"number" exists in the original input string : ax32aaa ->
这个暂时还有些疑惑
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。