一道java笔试题------字符串压缩算法

         这是一道java笔试题,据说不会做的话,连面试的机会都没有!

         题目是这样的:”请用JAVA实现字符串压缩算法。将字符串 aaabcdda 编程实现将其转换为 3a1b1c2d1a “

 

        我这个方法主要利用了递归算法。

 

       代码实现:

 

      

public class StringCompression {

 private StringBuffer sb = new StringBuffer();

 /**
  * aaabcdda—>3a1b1c2d1a
  *
  * @param sourceStr
  * @return 

  */
 public String compression(String sourceStr) {
  if (sourceStr == null || “”.equals(sourceStr)) {
   ;
  } else {
   //字符串长度
   int strLen = sourceStr.length();
   //字符串中第一个字符
   char firstChar = sourceStr.charAt(0);
   int count=1;
   //用于截串,字符串的起始位置
   int index = 0;
   if (strLen > 1) {
    for (int i = 1; i < strLen; i++) {
     char c = sourceStr.charAt(i);
     if (!String.valueOf(firstChar).equals(String.valueOf(c))) {
      index = i;
      break;
     }else{
       //统计相同字符的个数
       ++count;
     }
    }
    //相同字符的字符串,在sb中追加字符串长度和首字符
    if (index == 0) {
     return sb.append(strLen).append(firstChar)
       .toString();
    }
    sb.append(count).append(firstChar);

   } else if (strLen == 1) {  //字符串长度为1时
    return sb.append(“1”).append(firstChar).toString();
   }
   //起始索引必须小于等于结束索引,否则会报越界错误
   if (index <= strLen)
    compression(sourceStr.substring(index, strLen));
  }
  return sb.toString();

 }

 public static void main(String[] args) {
  StringCompression sc = new StringCompression();
  String sourceStr = “aaabcdda”;
  String resultStr = sc.compression(sourceStr);
  System.out.println(resultStr);
 }
}

 

    原文作者:小博
    原文地址: https://blog.csdn.net/fyqcdbdx/article/details/7325912
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞