[英]String Compression to Character ArrayList
我有一個字符串,我將其壓縮為帶有計數的字符數組。 我沒有得到字符串中的最后一個字符數。
public class StringComp {
public static void main(String[] args) {
String st = "aaabbccaaaaadddd";
ArrayList<Character> chars = new ArrayList<>();
int count = 1;
char ct;
for(int i = 0; i < st.length() - 1; i++) {
if(st.charAt(i) == st.charAt(i+1)) {
count++;
}else {
ct = Integer.toString(count).charAt(0);
chars.add(ct);
chars.add(st.charAt(i));
count = 1;
}
}
System.out.println(chars.toString());
}
}
我的 output:
[3, a, 2, b, 2, c, 5, a]
我的 output 應該是:
[3, a, 2, b, 2, c, 5, a, 4, d]
我似乎無法在我的代碼中找到錯誤。
您應該在循環之后添加最終計數:
...
for(int i = 0; i < st.length() - 1; i++) {
if(st.charAt(i) == st.charAt(i+1)) {
count++;
}else {
ct = Integer.toString(count).charAt(0);
chars.add(ct);
chars.add(st.charAt(i));
count = 1;
}
}
ct = Integer.toString(count).charAt(0);
chars.add(ct);
chars.add(st.charAt(st.length()-1));
另請注意,將計數存儲為單個Character
是一個壞主意。 如果計數大於 9 怎么辦?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.