目的:把字符串中連續重復的字符賜除掉。
輸入:序列:kkkhan888shioobo66
正確的返回結果應該是:hanshibo
思路解析
1 使用JAVA正則表達式,匹配出連續相同的字符或數字。
2 查找出匹配出來的序列,並取出來放到list里面
3 對list進行排序。把重復的序列排在前面。(該步可省略)
4找出連續重復的子序列,並把這些連續重復的子序列用空(字字符串)替換。
5 返回輸出。
code
public class Test { public static void main(String[] args) { String strings = matcher("kkkhan888shioobo66"); System.out.println(strings); } public static String matcher(String input) { //創建一個List List<String> list = new ArrayList<String>(); //創建匹配的模式 Pattern pattern = Pattern.compile("(.)\\1*"); //匹配器 Matcher matcher = pattern.matcher(input); //查找與該模式匹配的子序列。從"+kkkhan888shioobo66" 里面 查找出 與 此模式 "(.)\\1*" 相匹配的 子序列。如果存在,返回true,如果不存在,返回false. while (matcher.find()) { //返回匹配的子序列,並加入到list里面。 list.add(matcher.group()); } System.out.println(list); //對分好組的List,進行排序。根據指定比較器產生的順序對指定列表進行排序。把重復的序列排在前面。 Collections.sort(list, new Comparator<String>() { public int compare(String o1, String o2) { return o2.length() - o1.length(); } }); //找到連續重復的字符,加入到數組中。 String[] strings = list.toArray(new String[0]); //找出連續並且重復的子序列。並且把這些連續重復的子序列用空字符串替換。 for(int i=0 ;i<=strings.length-1;i++){ if(strings[i].length()>1){ System.out.println(strings[i]); input=input.replace(strings[i],""); System.out.println(input); } } System.out.println("最終結果:"+input); //返回把連續重復的字符賜除掉的字符序列。 return input; } }
java連續多位相同字符判斷的正則表達式
([0-9])\1{5} 或 ([\d])\1{5} 連續相同的6位數字 如:333333
([0-9a-zA-Z])\1{5} 連續相同的6位數字或字母 如:222222 cccccc ZZZZZZ
([\d])\1{2}([a-z])\2{2} 連續相同3位數字后根連續相同的三位小寫字母 如:222www
([\d])\1{2}([a-z])\2{2}|([a-z])\3{2}([\d])\4{2} 同上,但是能匹配數字+字母或字母+數字 如:222www 或 www222
自己可以擴展,要注意的就是 \1 \2代表位置,從左到右遞增
我是天王蓋地虎的分割線
參考:http://blog.csdn.net/atomcrazy/article/details/9087187