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

Here is my solution:

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;}};

But this solution is not passed.When i uncomment these two lines: if(s.size() == 0 || s.size() == 1) return s;, the code pass. i am confused, i think these code are equal.

1

Best Answer


When the length is 0 you get out of bounds access (j becomes a large number as it is unsigned).

The length 1 case should be safe to keep commented.