Solution: Encoding ASCII art
- [Instructor] Hopefully this challenge put a smile on your face and on your screens. The encodeString function here looks like a lot of code, unless maybe you did it in a more efficient way or at least a shorter way than I did. It's really not that tricky. Just a little tedious to keep track of everything. And this is where having well-named variables really comes in handy to make it clear what's going on. So here we have the stringVal that gets passed in and we want to ultimately loop through that. Along the way, we're going to keep track of a few things. So the first is our encodedList. This is what ultimately gets returned from the function. Then we have prevChar. This is so we know when the string has changed. If the current character doesn't match what the prevChar is, we know that we need to add something to the encodedList. And finally, we'll keep track of the count. This starts at zero and it just keeps track of how many characters we've gone through without seeing any change yet. Then we loop through the string. If the prevChar is not equal to the current character, great, we've seen a change. So this character is different than the last one that we saw. Also, notice that up here, the prevChar starts out as the first character of the string. So we're never going to detect a change when we're still on the first character. We have to wait until at least the second character to detect a change at all. So if there is a change, we add prevChar and the count to our encodedList. Reset the count. Now, in every iteration, we set prevChar equal to character, increment the count, add one to the count, and then we go through again. Outside of our loop, we've reached the end of the string, so we need to make sure that we record the last few characters. So now we append a new tuple to the end there as well. Finally, we return the encodedList. So now we have an encodeString function that can take in a string value and run length and code it. Finally, we need to make our decodeString function. Fortunately, this one is way more straightforward. All we have to do is go through each item in the encodedList, take that item, multiply it by the count, and then add it to our string and return that. So let's suss it out. Great. We have our smiley face. I also included this very simple test case here because it can be difficult to see if there are any bugs when the strings are very large, like with this ASCII art smiley face.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。