zoukankan      html  css  js  c++  java
  • Leetcode 344. 反转字符串

    1.题目描述

    编写一个函数,其作用是将输入的字符串反转过来。

    示例 1:

    输入: "hello"
    输出: "olleh"

    示例 2:

    输入: "A man, a plan, a canal: Panama"
    输出: "amanaP :lanac a ,nalp a ,nam A"
    

    2.复杂解法

    //string转化为vector数组处理
    //当时不知道string可以直接下标访问。。
    class Solution {
    public:
        string reverseString(string s) {
            //直接返回
            if(s.size()==0 || s.size()==1) return s;
            
            vector<char> temp;
            //string to vector<char>
            for(auto a : s){
                temp.push_back(a);
            }
            //reverse
            int size = temp.size();
            for(int i = 0; i<=size/2-1;++i){
                swap(temp[i],temp[size-1-i]);
            }
            //vector<char> to string
            string res;
            for(auto b : temp){
                res += b;
            }
            return res;
        }
    };

    3.简洁解法

    • string可以直接用下标或迭代器访问字符串中的字母。
    class Solution {
    public:
        string reverseString(string s) {
            int sz = s.size();
            for (int i = 0; i < sz/2; ++i){
                swap(s[i], s[sz-i-1]);
            }
            return s;
        }
    };
  • 相关阅读:
    STM32 变量无法赋值问题
    ROS 多台计算机联网控制机器人
    Content-Disposition
    Arrays.asList()与toArray()
    length与size()
    computeIfAbsent
    共享锁、排他锁与意向锁
    行锁、页面锁与表锁
    classpath是什么
    start、run、join
  • 原文地址:https://www.cnblogs.com/paulprayer/p/10132660.html
Copyright © 2011-2022 走看看