每日一题 为了工作 2020 0410 第三十九题

/**
 * 问题:字符串的统计字符串
 * 	   给定一个字符串str, 返回str 的统计字符串。例如, "aaabbadddffc"的统计字符串为
 * "a_3_b_2_a_l_d_ 3_f_2_c l"。
 * 
 * 解答:
 * 1.如果str为空,那么统计字符串不存在。
 * 2.如果str不为空。首先生成 String类型的变量 res, 表示统计字符串, 还有整型变量num,
 *   代表当前字符的数量。初始时字符串 res只包含 str的第 0个字符(str[O]), 同时 num=1。
 * 3.从str[1]位置开始, 从左到右遍历 str, 假设遍历到 i位置。如果str[i]=str[i-1],
 *   说明当前连续出现的字符(str[i-1])还没结束, 令 num++, 然后继续遍历下一个字符。如
 *   果str[i] != str[i-1], 说明当前连续出现的字符(str[i-1])已经结束,令
 *   res=res+"_"+num+"_"+str[i],然后令 num=1, 继续遍历下一个字符。以题目给出的
 *   例子进行说明, 在开始遍历"aaabbadddffc"之前, res= "a", num=1。遍历str[1~2]时
 *   字符'a'一直处在连续的状态, 所以num增加到3。遍历str[3]时,字符'a'连续状态停止,令
 *   res = res+"_"+"3"+"_"+"b"(即"a_3_b"),num=1。遍历str[4], 字符'b'在连
 *   续状态,num增加到2。遍历str[5]时, 字符'b'连续状态停止, 令res为"a_3_b_2_a",
 *   num=1。依此类推, 当遍历到最后一个字符时, res为"a_3_b_2_a_l_d_3_f_2_c", 
 *   num=1。
 * 4.对于步骤3中的每一个字符, 无论连续还是不连续, 都是在发现一个新字符的时候再将这个字符连
 *   续出现的次数放在res的最后。所以当遍历结束时, 最后字符的次数还没有放入res, 所以最后
 *   令res=res+"_"+num。在例子中当遍历结束 res为"a_3_b_2_a_l_d_3_f_2_c",num=1,
 *   最后需要把 num加在 res后面,令 res变为"a_3_b_2_a_l_d_3_f_2_c_1",然后再返回。
 * 
 * @author 雪瞳
 *
 */

  

public class GetCountStringElements {
	
	public String getCountStringElements(String str){
		String res;
		int num = 0;
		
		if(str == null || str.equals("")){
			return null;
		}
		char[] chars = str.toCharArray();
		
		res = String.valueOf(chars[0]);
		num = 1;
		for(int i= 1;i<chars.length;i++){
			if(chars[i]==chars[i-1]){
				num ++;
			}
			if(chars[i] != chars[i-1]){
				res = res+"_"+num+"_"+String.valueOf(chars[i]);
				num = 1;
			}
		}
		
		return res+"_"+num;
	}
}

  

public class TestGetCountStringElements {

	public static void main(String[] args) {
		GetCountStringElements get = new GetCountStringElements();
		String str= "aaaabbcddacc";
		System.out.println(get.getCountStringElements(str));
	}
}

  

* 运行结果

 

猜你喜欢

转载自www.cnblogs.com/walxt/p/12672826.html
今日推荐