package com.abuge;
/**
* 需求:
* 利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能,若压缩后的字符串没有变短,则返回原先的字符串。
* 如:aabccccaaa会变为a2b1c5a3
* @author AbuGe
*
*/
public class CompressDemo
{
public static String compressDemo1(String str)
{
/**
* 1、定义一个字符串变量mystr存储临时字符串
* 2、定义记录字符个数的变量count,定义当前指向的字符变量last
* 分析:
* 时间复杂度:
* 对于字符串的拼接,时间复杂度为O(n * n)所以整个时间复杂度为x + (p - x)n * n,近似为O(p + n * n)
* 其中x为整个字符串中if语句执行的次数, n为复制字符串的次数
*/
String mystr = "";
int count = 1;
char last = str.charAt(0);
//遍历字符串
for(int i = 1; i < str.length(); i++)
{
if(str.charAt(i) == last)
{
count++;
}else
{
//注意char + int转成字符串时,""要放在前面,否则会先计算+,从而产生错误的结果
mystr += "" + last + count;
last = str.charAt(i);
count = 1;
}
}
mystr += "" + last + count;;
return mystr;
}
//利用StringBuffer优化,时间复杂度和空间复杂度都为O(N)
public static String compressDemo2(String str)
{
/**
* 检测压缩后的字符串是否变短
*/
int size = compressStr(str);
if(size >= str.length())
{
return str;
}
String mystr = "";
int count = 1;
char last = str.charAt(0);
//构建字符串缓冲区
StringBuffer sb = new StringBuffer();
for(int i = 1; i < str.length(); i++)
{
if(last == str.charAt(i))
{
count++;
}else
{
sb.append(last);
sb.append(count);
last = str.charAt(i);
count = 1;
}
}
return sb.toString() + last + count;
}
//计算压缩后的字符串长度
public static int compressStr(String str)
{
int size = 0;
int count = 1;
char last = str.charAt(0);
for(int i = 1; i < str.length(); i++)
{
if(last == str.charAt(i))
{
count++;
}else
{
size = size + 1 + String.valueOf(count).length();
last = str.charAt(i);
count = 1;
}
}
size += 1 + String.valueOf(count).length();
return size;
}
//利用数组不用StringBuffer,时间复杂度和空间复杂度都为O(N)
public static String compressDemo3(String str)
{
/**
* 检测压缩后的字符串是否变短
*/
int size = compressStr(str);
if(size >= str.length())
{
return str;
}
String mystr = "";
int count = 1;
char last = str.charAt(0);
int index = 0;
//构建字符串缓冲区
char[] array = new char[size];
for(int i = 1; i < str.length(); i++)
{
if(last == str.charAt(i))
{
count++;
}else
{
index = setChar(array, last, index, count);
last = str.charAt(i);
count = 1;
}
}
setChar(array, last, index, count);
return String.valueOf(array);
}
//设置字符数组
public static int setChar(char[] array, char last, int index, int count)
{
array[index] = last;
index++;
//将字符数目转换成字符串然后转换成字符数组
char[] cnt = String.valueOf(count).toCharArray();
//从最高位到最低位复制字符
for(char ch : cnt)
{
array[index] = ch;
index++;
}
return index;
}
public static void main(String[] args)
{
String str = "aabccccaaa";
System.out.println(compressDemo1(str));
System.out.println(compressDemo2(str));
System.out.println(compressDemo3(str));
}
}
《程序员面试金典》之压缩字符串
最新推荐文章于 2020-08-31 11:47:20 发布