zoukankan      html  css  js  c++  java
  • 1.2原串翻转

    题目描述

    请实现一个算法,在不使用额外数据结构和储存空间的情况下,翻转一个给定的字符串(可以使用单个过程变量)。
    给定一个string iniString,请返回一个string,为翻转后的字符串。保证字符串的长度小于等于5000。

    测试样例

    "This is nowcoder"
    返回:"redocwon si sihT"
     
    解法
    //注意不分配额外空间
    //①C++
    //1.2原串翻转
     1 class Reverse {
     2 public:
     3     string reverseString(string iniString) {
     4         // write code here
     5         int strLen = iniString.size();
     6         if(strLen < 0)
     7         {
     8             return NULL;
     9         }
    10         int left = 0;
    11         int right = strLen-1;
    12         char ch;
    13         for (; left <right;)
    14         {
    15             ch = iniString[left];
    16             iniString[left] = iniString[right];
    17             iniString[right] = ch;
    18             ++left;
    19             --right;
    20         }
    21         return iniString;
    22     }
    23 };
    //Java
     1 import java.util.*;
     2 public class Reverse
     3 {
     4     public String reverseString(String iniString)
     5     {
     6         StringBuilder sb = new StringBuilder(iniString);
     7         int low = 0;
     8         int high = iniString.length() - 1;
     9         char temp = '';
    10 
    11         while(low < high)
    12         {
    13             temp = sb.charAt(low);
    14             sb.setCharAt(low, sb.charAt(high));
    15             sb.setCharAt(high, temp);
    16             low++;
    17             high--;
    18         }
    19         return sb.toString();
    20     }
    21 }
    //C++ 超精简版
    1 class Reverse {
    2 public:
    3     string reverseString(string iniString)
    4     {
    5             string temp(iniString.crbegin(),iniString.crend());
    6             return temp;
    7     }
    8 }; 
     





  • 相关阅读:
    linux System V IPC Mechanisms
    linux pipes
    linux create a process
    linux processes identifiers
    linux processes
    beaglebone-black reference url
    git commit steps(1)
    hadoop hadoop install (1)
    OpenWrite方法打开现有文件并进行写入
    OpenRead方法打开文件并读取
  • 原文地址:https://www.cnblogs.com/gxcdream/p/4919870.html
Copyright © 2011-2022 走看看