首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

关于“将字符串中邻近相同的子串合并为一个子串的代码”实现

2012-11-09 
关于“将字符串中相邻相同的子串合并为一个子串的代码”实现?在网上看到一个面试题,要求?因为最近在看js的正

关于“将字符串中相邻相同的子串合并为一个子串的代码”实现

?在网上看到一个面试题,要求

?因为最近在看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;}}

?

热点排行