压缩字符串的程序(Program to compress a string)

编程入门 行业动态 更新时间:2024-10-23 07:17:43
压缩字符串的程序(Program to compress a string)

我正在编写一个使用行程编码压缩字符串的程序。

例如,对于输入“aaabbccccddd”,输出应为“a3b2c4d3”。

目前该程序没有输出。

public static void main(String[] args) { String words1 = "aabbbcccc"; String words2 = compress(words1); System.out.println(words2); } private static String compress(String w1) { StringBuilder w2 = new StringBuilder(); int k = 0; for (int i = 0; i < w1.length(); ) { k++; if(i+1>w1.length() || w1.charAt(i) != w1.charAt(i+1)) { w2.append(w1.charAt(i)); w2.append(k); k = 0; } } return ((w2.length() > w1.length())? w1: w2.toString()); }

输出在IntelliJ中没有显示,我无法弄清楚为什么! 也尝试没有StringBuilder 。 甚至在没有StringBuilder情况下尝试将返回类型更改为void ,以防它处理String时出现问题。 相同,没有结果。

I'm writing a program that compresses strings using run-length encoding.

E.g. for input "aaabbccccddd", output should be "a3b2c4d3".

Currently the program shows no output.

public static void main(String[] args) { String words1 = "aabbbcccc"; String words2 = compress(words1); System.out.println(words2); } private static String compress(String w1) { StringBuilder w2 = new StringBuilder(); int k = 0; for (int i = 0; i < w1.length(); ) { k++; if(i+1>w1.length() || w1.charAt(i) != w1.charAt(i+1)) { w2.append(w1.charAt(i)); w2.append(k); k = 0; } } return ((w2.length() > w1.length())? w1: w2.toString()); }

Output shows nothing in IntelliJ and I can't figure out why!! Also tried without StringBuilder. Even tried without StringBuilder and changing the return type to void in case it was a problem with handling a String. Same, no result.

最满意答案

正如伊兰所说,你忘记了i++部分。 此外, i+1>w1.length()应为i+1>=w1.length() 。 它应该适用于这两个变化。

private static String compress(String w1) { StringBuilder w2 = new StringBuilder(); int k = 0; for (int i = 0; i < w1.length(); i++) { k++; if(i+1>=w1.length() || w1.charAt(i) != w1.charAt(i+1)) { w2.append(w1.charAt(i)); w2.append(k); k = 0; } } return ((w2.length() > w1.length())? w1: w2.toString()); }

As Eran said, you forgot the i++ part. Also, i+1>w1.length() should be i+1>=w1.length(). It should work with those two changes.

private static String compress(String w1) { StringBuilder w2 = new StringBuilder(); int k = 0; for (int i = 0; i < w1.length(); i++) { k++; if(i+1>=w1.length() || w1.charAt(i) != w1.charAt(i+1)) { w2.append(w1.charAt(i)); w2.append(k); k = 0; } } return ((w2.length() > w1.length())? w1: w2.toString()); }

更多推荐

本文发布于:2023-07-15 19:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117536.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   程序   Program   compress   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!