---
title: "一个关于字符串操作的算法题"
author: "Eastsun"
date: "2007-08-01T19:46:50Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2007-08-01T19:46:50Z"
id: 107884
url: "https://eastsun.iteye.com/blog/107884"
---

最近在网上看到一道关于字符串操作的算法题,不过原题的表述以及给出的数据都有问题.这里我给出修正后的题目:

**题目: 设计一个方法 String encode(String str),对字符串str进行如下转换操作为一个新字符串:**

         **逐个扫描str的每个字符,**

         **1.若当前字符为'\_',则添加"\\UL"到新字符串; 否则:**

         **2.若当前字符表示一大于0的数字N,且该字符不是最后一个字符,则将后继字符添加N+1次到新字符串;否则:**

         **3.直接添加当前字符到新字符串.**

         **并且用一个字符'\_'将相邻的变换隔开**

         **并设计一个String decode(String code)方法执行encode的逆操作,即将由encode(str)方法返回的字符串还原为str.**

       encode方法的设计没有任何难度,只需要把题目"直译"成程序代码就OK了,有难度的地方在于decode方法.注意到字符串中的字符在encode之后的新字符串中是由'\_'分开的,并且原字符串中的每个字符只由这个字符串变换后的字符串以及其后继字符有关,因此我们很容易可以想到先将编码后的字符串按'\_'分解成一系列字符串,其中每个字符串对应原字符串的一个字符,然后从后向前一个个求出其所表示的字符.算法的大体想法就是这样,只有一点要注意:类似"4\_"这种数字后跟'\_'的情形会被编码成一列连续的"\_\_\_\_\_",应该区分出这种情形并加以处理 .

       其实如果对压缩算法有所了解的话,很容易看出这个题目其实是行程编码( Run-Length Encoding )的一个变形.

下面给出本题的代码:

java 代码

01. /\**
02. \*author: Eastsun
03. \*version: 1.0 2007/8/1
04. \*/
05. import  java.util.Scanner;
06. public   class  StringCode{
07. public   static   void  main(String\[] args){
08. Scanner s = new  Scanner(System.in);
09. while ( true ){
10. String text =s.next();
11. if ( "exit" .equalsIgnoreCase(text))  break ;
12. String code =encode(text);
13. boolean  flags = true ;        //用于检测decode是否正确工作的标记
14. try {
15. if (!decode(code).equals(text)) flags = false ;
16. } catch (IllegalStateException e){
17. flags = false ;
18. }
19. if (flags){
20. System.out.println( "Code :"  +code);
21. }
22. else {
23. System.out.println( "Error code :"  +code);
24. }
25. }
26. }
27. private   static   final  String ESC\_S =  "\\\\UL" ;
28. private   static   final   char    ESC\_C = '\_';
29. /\**
30. \*将编码后的字符串还原为原字符串
31. \*@throws IllegalStateException 如果参数str不是一个有效的编码字符串
32. \*/
33. public   static  String decode(String str) throws  IllegalStateException{
34. StringBuilder sb = new  StringBuilder();
35. char  next = 0xffff ;
36. int  end =str.length(), start;
37. while (end&gt; 0 ){
38. if (next==ESC\_C&&str.charAt(end- 1 )==ESC\_C){
39. for (start =end - 1 ;start&gt; 0 &&str.charAt(start- 1 )==ESC\_C;start--);
40. if (start!= 0 ) start ++;
41. }
42. else {
43. start =str.lastIndexOf(ESC\_C,end - 1 ) + 1 ;
44. }
45. String code =str.substring(start,end);
46. if (code.equals(ESC\_S)){
47. next = ESC\_C;
48. }
49. else   if (end-start== 1 ){
50. next = code.charAt( 0 );
51. }
52. else {
53. for ( int  index = 0 ;index
54. if (code.charAt(index)!= next)  throw   new  IllegalStateException( "Illegal code: \[" +start+ "," +end+ "]" );
55. next =( char )(' 0 '+end-start- 1 );
56. }
57. sb.insert( 0 ,next);
58. end =start - 1 ;
59. }
60. return  sb.toString();
61. }
62. /\**
63. * 将str编码为新的字符串
64. \*/
65. public   static  String encode(String str){
66. StringBuilder sb = new  StringBuilder();
67. for ( int  index = 0 ;index
68. char  c =str.charAt(index);
69. if (c==ESC\_C){
70. sb.append(ESC\_S);
71. }
72. else   if (c&gt;' 0 '&&c&lt;=' 9 '&&index+ 1
73. char  next =str.charAt(index+ 1 );
74. for ( int  count =c-' 0 ';count&gt;= 0 ;count--)
75. sb.append(next);
76. }
77. else {
78. sb.append(c);
79. }
80. if (index+ 1
81. }
82. return  sb.toString();
83. }
84. }