题解 | #字符串压缩算法#

字符串压缩算法

http://www.nowcoder.com/practice/2ff3d36b4d4a4bfeb1a7d64f3cc55c15

import java.util.Scanner;

public class Main{

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String str = in.nextLine();
    String res = compress(str);
    System.out.println(res);
}

public static String compress(String str){
    int count = 0;
    String res = "";
    if(str.length()==1){
        res = str;
    }
    else{
        for(int i=1; i<str.length(); i++){
            String s = str.substring(i, i+1);


            if(i==str.length()-1){
                if(s.equals(str.substring(i-1, i))){
                    count++;
                    if(count!=0){
                        res += count + str.substring(i-1, i);
                    }
                    else{
                        res += str.substring(i-1, i);
                    }
                }
                else{
                    if(count!=0){
                        res += count + str.substring(i-1, i);
                    }
                    else{
                        res += str.substring(i-1, i);
                    }
                    res += s;
                }
            }
            else{
                if(s.equals(str.substring(i-1, i))){
                    count++;
                }
                else{
                    if(count!=0){
                        res += count + str.substring(i-1, i);
                    }
                    else{
                        res += str.substring(i-1, i);
                    }
                    count = 0;
                }
            }

        }
    }

    return res;
}

}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 11:15
点赞 评论 收藏
分享
06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 12:10
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务