zoukankan      html  css  js  c++  java
  • 2.字符串翻转

    思路很重要:

    获取字符串长度,两头交换相应字符。

    核心代码:

     1 void swap(char &x,char &y)
     2 {
     3     x = x^y;
     4     y = x^y;
     5     x = x^y;
     6 }
     7 void reverse(char *s)
     8 {
     9     int i = 0;
    10     int len = strlen(s);
    11     for(i = 0;i < len/2; ++i)
    12         swap(s[i],s[len-i-1]);
    13 }

    示例代码:

     1 #include <cstring>
     2 #include <iostream>
     3 using namespace std;
     4 void swap(char &x,char &y)
     5 {
     6     x = x^y;
     7     y = x^y;
     8     x = x^y;
     9 }
    10 void reverse(char *s)
    11 {
    12     int i = 0;
    13     int len = strlen(s);
    14     for(i = 0;i < len/2; ++i)
    15         swap(s[i],s[len-i-1]);
    16 }
    17 int main()
    18 {
    19     char str[20] = "hello,world";
    20     reverse(str);
    21     cout<<str<<endl;
    22 }
    View Code
  • 相关阅读:
    Python保留最后N个元素
    STL算法
    STL迭代器
    STL容器
    C++总结1
    牛客剑指Offer2
    Vue第一天
    UML
    Java继承和组合代码
    Java15后的sealed阻止继承滥用
  • 原文地址:https://www.cnblogs.com/sxmcACM/p/4776989.html
Copyright © 2011-2022 走看看