我正在编写一个使用行程编码压缩字符串的程序。
例如,对于输入“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()); }更多推荐
发布评论