关于leetcode中“反向字符串”的解决方案

时间:2016-09-05 07:53:52

标签: c++ algorithm

https://leetcode.com/problems/reverse-string/

这是我的解决方案:

func fillPixelBufferFromImage(image: UIImage, pixelBuffer: CVPixelBufferRef) {
    CVPixelBufferLockBaseAddress(pixelBuffer, 0)

    let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer)
    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()

    // Create CGBitmapContext
    let context = CGBitmapContextCreate(
        pixelData,
        Int(image.size.width),
        Int(image.size.height),
        8,
        CVPixelBufferGetBytesPerRow(pixelBuffer),
        rgbColorSpace,
        CGImageAlphaInfo.PremultipliedFirst.rawValue
    )

    // Draw image into context
    CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage)

    CVPixelBufferUnlockBaseAddress(pixelBuffer, 0)
}

但是这个解决方案没有通过。 当我取消注释这两行:class Solution { public: string reverseString(string s) { // if(s.size() == 0 || s.size() == 1) // return s; string::size_type i = 0; string::size_type j = s.size() - 1; while (i < j) { char temp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; } return s; } }; 时,代码通过。我很困惑,我认为这些代码是平等的。

1 个答案:

答案 0 :(得分:5)

当长度为0时,您将超出边界访问权限(j变为大数字,因为它是无符号的)。

长度为1的情况应该是安全的,以保持评论。