在网上看到一个面试题,要求
写道
将字符串中相邻相同的子串合并为一个子串,如"12342343454565678789" -- "123456789"
因为最近在看js的正则表达式,觉得java也是可以实现的,结果碰巧就实现了。用了两种方法,可其实原理都是一样的。个人觉得这样写效率比较高,各位觉得呢?
package regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 将字符串中相邻相同的子串合并为一个子串,如"12342343454565678789" -- "123456789"
*/
public class StringMerge {
public static void main(String[] args) {
// System.out.println(tt(6));
mergeString2("1234234345456567878911111111111111112343333333333");
System.out.println("----");
mergeString("1234234345456567878911111111111111112343333333333");
}
public static void mergeString(String str) {
String regex = "(\\d+)\\1";
String temp1 = replace(regex, str);
int len2 = str.length();
while (temp1.length() != len2) {
//System.out.println(len2 + "--" + temp1.length());
len2 = temp1.length();
temp1 = replace(regex, temp1);
}
System.out.println("方法一:"+temp1);
}
/**
* 用appendReplacement ..方法一:
* @param str
*/
public static String replace(String regex, String str) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "$1");
}
m.appendTail(sb);
//System.out.println(sb.toString());
return sb.toString();
}
public static void mergeString2(String str) {
String regex = "(\\d+)\\1";
String temp1 = replace2(regex, str);
int len2 = str.length();
while (temp1.length() != len2) {
//System.out.println(len2 + "--" + temp1.length());
len2 = temp1.length();
temp1 = replace2(regex, temp1);
}
System.out.println("方法一:"+temp1);
}
/**
* 用replaceAll实现,方法二:
* @param regex
* @param str
* @return
*/
public static String replace2(String regex, String str) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
String temp = m.replaceAll("$1");
return temp;
}
}