F欄 フリーター dossyのプログラミング初心者日記  〜ええんやで〜

自分が思ったこと、試したこと、outputしたことを書き殴ってやる。夢は、賢い人になること!!!

leet code 38. Count and Say の解答:問題文解説

これむずすぎへんか??

 

と思った。

 

まず、問題が初見だと意味不明でした。。。。

問題文の意図を汲み取るのに時間がかかりました。

まず、問題の意味がわからなければ問題は解けないのでホント苦労の連続ですね。

 

hatena blogなどで解答を書いている人もいるみたいですが、自分もoutputのために書いておきます!!!

イエィ!!

 

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.

Note: Each term of the sequence of integers will be represented as a string.

 

----------------------------------------------------

intの整数が与えられます。

 

2なら、1のvalue 11を参照します。

11は1が2つあります。ですが、英語では 1が2つあるではなく,2つあるよ1がと表示します。なので valueは 21 (two one)となる。

 

3なら、2のvalue 21を参照します。

21は2が1つ1が1つあります。 ですが、英語では〇個あるよ〇〇が と表示します!!

この時、1つあるよ2が + 1つあるよ1が => 1211(one two one one)  となります。

 

問題の解説は終わり!!

 

次、codeです。

自分では考えきれませんでしたので、他人のコードを拝借してときました。

激ムズやでホンマ。easyやのに。。。。。

 

func countAndSay(n int) string {
seq := "1"
for i := 1; i < n; i++ {
seq = next(seq)
}
return seq
}

func next(seq string) string { //次の要素(next)のstringを返す
i := 0
nextSeq := ""
for i < len(seq) { //length分回す
count := 1 //nextの要素用
for i < len(seq)-1 && seq[i] == seq[i+1] { //0 < 3 && nowとnextが同じなら
//0<3は3より奥のseqのlengthより多い要素を調べないようにしている
count++
i++
}
nextSeq += strconv.Itoa(count) + string(seq[i])
// strconv.Itoa(count)が個数 + string(seq[i])が値
i++
}
return nextSeq
}

 

 

 

むずかったよっていう備忘録を残しておきます。。

1年後こんなもん楽勝やで!と思っていたいので、書いておきます!!!!