计算字符中相邻位置相同字符的个数

来源:互联网 发布:旅行箱 知乎 编辑:程序博客网 时间:2024/05/21 10:03

题目:计算字符中相邻位置相同字符的个数

       例如:abbbccdfgk  输出a1b3c2d1f1g1k1

package cn.zyz.a_zy;public class Test1 {public static void main(String[] args) {read1();}public static void read1() {String str = "abbbccdfgk";int i = 0 , count = 1 , j;   //i是遍历到的位置,count是出现的数量(因为不和自身比较,所以count从1开始),j是i位置后一个元素/** * 如果还没有遍历完str字符串 */while(i < str.length()) {for(j = i+1; j < str.length(); j++) {  if(str.charAt(i) != str.charAt(j)) {  //如果相邻不相等 ,停止for循环break;}count++;   //相等,count加1}System.out.print(str.charAt(i)+""+count+" ");  //输出字符和出现的次数count = 1;   //count重置i = j;  }}}

输出结果为:a1 b3 c2 d1 f1 g1 k1

2.用递归实现

public class Test2 {public static void main(String[] args) {ToStr toStr = new ToStr();toStr.toStr2("abbccccccddffffgggh");}}class ToStr{private static int i = 0, j = 1 , count = 1;public void toStr2(String str) {if(i < str.length()) {if(j == str.length() || str.charAt(i) != str.charAt(j)) {System.out.print(str.charAt(i)+""+count+" ");  //输出count = 1;i = j;  //i从j的位置继续遍历 }else {count++;  //如果等于,count++}j++;   //j继续往下移动toStr2(str);  //递归电泳}}}
输出结果为:a1 b2 c6 d2 f4 g3 h1

阅读全文
0 0