• leetcode 344. Reverse String


    Write a function that takes a string as input and returns the string reversed.

    Example:
    Given s = "hello", return "olleh".

    class Solution(object):
        def reverseString(self, s):
            """
            :type s: str
            :rtype: str
            """
            return s[::-1]

    其他解法:

    public class Solution {
        public String reverseString(String s) {
            byte[] bytes = s.getBytes();
            int i = 0;
            int j = s.length() - 1;
            while (i < j) {
                bytes[i] = (byte) (bytes[i] ^ bytes[j]);
                bytes[j] = (byte) (bytes[i] ^ bytes[j]);
                bytes[i] = (byte) (bytes[i] ^ bytes[j]);
                i++;
                j--;
            }
            return new String(bytes);
        }
    }

    用到了交换不用任何空间。

    public class Solution {
        public String reverseString(String s) {
            byte[] bytes = s.getBytes();
            int i = 0;
            int j = s.length() - 1;
            while (i < j) {
                byte temp = bytes[i];
                bytes[i] = bytes[j];
                bytes[j] = temp;
                i++;
                j--;
            }
            return new String(bytes);
        }
    }
    class Solution {
    public:
        string reverseString(string s) {
            int i = 0, j = s.size() - 1;
            while(i < j){
                swap(s[i++], s[j--]); 
            }
            
            return s;
        }
    };
  • 相关阅读:
    复制对象
    element.classList属性及方法应用
    Object.defineProperty
    965. Univalued Binary Tree
    700. Search in a Binary Search Tree
    561, Array Partition Ⅰ
    933. Number of Recent Calls
    999.Available Capture for rook
    961. N-Repeated Element in Size 2N Array
    709. To Lower Case
  • 原文地址:https://www.cnblogs.com/bonelee/p/8511727.html
Copyright © 2020-2023  润新知