JAVA-字符串连续出现字母进行压缩

字符串连续出现的字母进行压缩

举例:输入为xxxyyyyyyz

压缩后为 3x6yz

解题思路:

通过在对输入字符串的遍历循环中借助一个StringBuffer变量sb进行字符串的拼接

在遍历中的firstChar每次都会取到没有遍历字符串中的第一个位置,一开始从位置0开始

for循环遍历也是从i=1开始,因为已经取了firstChar为第0个位置了

count变量初始值为1,是用来统计每一个字符的个数的,当s变量和firstChar变量相同时候,count+1

当出现了匹配的字符s和firstChar不同时候就开始判断count是否大于1,大于1就使用StringBuffer的append方法,拼接字符串

并且拼接完成之后,count重新归位1.

JAVA-字符串连续出现字母进行压缩_第1张图片

/**
 * @ Author zhangsf
 * @CreateTime 2019/11/22 - 10:14 PM
 */
package com.bjut.leetcode;

import java.util.Scanner;
public class ZipData {
    public static void main(String[] args) {
        System.out.println("请输入字符串:");
        Scanner sc=new Scanner(System.in);
        String str=sc.nextLine();
        String rex =zipData(str);
        System.out.println(rex);
//        while (sc.hasNextLine()){
//            String str=sc.nextLine();
//            String rex =zipData(str);
//            System.out.println(rex);
//        }
    }
    public static String zipData(String str){
        StringBuilder sb= new StringBuilder();
        //字符串中第一个字符
        char firstChar=str.charAt(0);
        //字符数量默认为1
        int count=1;
        //数组下标从1开始
        for(int i = 1; i < str.length(); i++){
            char s=str.charAt(i);//字符串中第2个字符
            if(firstChar==s){//如果第1个字符和第2个相等,数量+1
                count++;
            }else{//如果第1个字符和第2个字符不相等
                if(count>1){//数量大于1
                    sb.append(count);//数量追加到StringBuilder中
                    sb.append(firstChar);//把第2个字符赋值给第一个字符的值追加到StringBuilder中  
                     System.out.println("当前的匹配的字符下标位置为"+i+"---"+s+"此时sb字符串为"+sb);
                    count=1;//重新初始化数量为1
                }else{//如果第1个字符和第2个字符不相等,并且数量不大于1,把第一个字符追加到StringBuilder中
                    sb.append(firstChar);
                }
            }
            firstChar=s;//把第2个字符赋值给第一个字符
        }
        if (count>1) {//如果数量大于1,把count追加到StringBuilder中
            sb.append(count);
        }
        sb.append(firstChar);//最后把字符追加到StringBuilder中
        return sb.toString();
    }
}


 

你可能感兴趣的:(牛客&Leetcode)