You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Use the Standard Library's reverse Function
    The easiest way is to leverage the reverse function 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; 
        } 
    };
    
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:27:47