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

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

       例如: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值