LeetCode No.38 Count and Say | #StringBuffer

Q:

The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11
11 is read off as "two 1s" or 21
21 is read off as "one 2, then one 1" or 1211
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.

A:



public class Solution {
public String countAndSay(int n) {
    StringBuffer sb = new StringBuffer("1");
    for(int i = 1; i < n; i++) {
        int count = 1;
        StringBuffer temp = new StringBuffer();
        int len = sb.length();
        for(int j = 1; j < len; j++) {
            if(sb.charAt(j) != sb.charAt(j - 1)) {
                temp.append(count);
                temp.append(sb.charAt(j - 1));
                count = 1;
            }
            else {
                count++;
            }
        }
        temp.append(count);
        temp.append(sb.charAt(len - 1));
        sb = temp;
    }
    return sb.toString();
    }
}

String vs StringBuffer:

String是final類,不能被繼承。是不可變對(duì)象,修改值需要?jiǎng)?chuàng)建新的對(duì)象,然后保存新的值,舊的對(duì)象垃圾回收,影響性能:在字符串鏈接的時(shí)候,也需要建立一個(gè)StringBuffer,然后調(diào)用append(),最后StringBuffer toString()。
StringBuffer是可變對(duì)象,修改時(shí)不需要重新建立對(duì)象。
初始創(chuàng)建需要construction: StringBuffer sb = new StringBuffer();,初始保存一個(gè)null。賦值的時(shí)候可以使用sb.append();,不可以直接用賦值符號(hào):sb="***"; //error。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容