p49 reverse text (leetcode 344)

A: problem-solving ideas

Time: The (n), Space: The (1)

Two: Complete code examples (C ++ version and the Java version)

C++:

class Solution {
public:
    void reverseString(vector<char>& s) 
    {
        int i = 0, j = s.size() - 1;

        for (; i < j; i++, j--)
        {
            swap(s[i],s[j]);
        }
    }
};

Java:

class Solution {
    public void reverseString(char[] s) 
    {
          int i=0,j=s.length-1;
          
          for(;i<j;i++,j--)
          {
              char temp=s[i];
              s[i]=s[j];
              s[j]=temp;
          }
    }
}

 

Guess you like

Origin www.cnblogs.com/repinkply/p/12512231.html