LeetCode 344反转字符串:数组初始化后元素超出预期求助
Hey there! Let's break down why your code is producing those unexpected extra characters and fix it step by step.
问题根源
The core issue here is missing the null terminator ('\0') for your C-style character array. When you allocate memory with new char[s.length()], you're only creating space for the reversed characters—but C-style strings require a trailing '\0' to signal the end of the string.
When you construct the string from array, the constructor keeps reading memory until it hits a '\0'. Since you didn't add one, it ends up grabbing random garbage data from adjacent memory, which is exactly those weird extra characters you're seeing.
Quick Fix for Your Existing Code
To fix this, you just need to allocate one extra byte for the null terminator and manually add it after filling the array. Also, don't forget to free the allocated memory to avoid leaks:
class Solution { public: string reverseString(string s) { // Allocate +1 byte for the null terminator char *array = new char[s.length() + 1]; for(int i=0;i<s.length();i++) { array[i] = s[s.length()-i-1]; } array[s.length()] = '\0'; // Add the required null terminator string strlist(array); printf("%s\n",strlist.c_str()); delete[] array; // Free the allocated memory to prevent leaks return strlist; } };
Better Approaches (No Manual Memory Allocation)
Your current approach uses unnecessary dynamic memory. Here are two cleaner, more efficient ways to solve this problem:
Use the Standard Library's
reverseFunction
The easiest way is to leverage thereversefunction from the<algorithm>header—it handles all the heavy lifting for you:#include <algorithm> #include <iostream> class Solution { public: string reverseString(string s) { reverse(s.begin(), s.end()); cout << s << endl; // Safer than printf for C++ strings return s; } };Two-Pointer Swap (In-Place, No Extra Memory)
If you want to implement the reversal manually without extra memory, use a two-pointer technique to swap characters from the start and end moving towards the center:#include <iostream> class Solution { public: string reverseString(string s) { int left = 0; int right = s.size() - 1; while (left < right) { swap(s[left], s[right]); left++; right--; } cout << s << endl; return s; } };
Both of these methods avoid the null terminator issue entirely and are more idiomatic C++ code.
内容的提问来源于stack exchange,提问作者CY.Lee

