• 344. Reverse String


    原文题目:

    344. Reverse String

    读题:

    题目就是将一个字符串进行翻转操作,解法有4种

    1)用库函数reverse

    2)从后往前进行复制

    3)头尾字符进行交换

    4)用栈实现

    库函数法:

    class Solution 
    {
    public:
    	string reverseString(string s) 
    	{
    		reverse(s.begin(),s.end());
    		return s;
    
    	}
    };
    

    复制法:

    class Solution 
    {
    public:
    	string reverseString(string s) 
    	{
    		string result;
    		int len = s.length();
    		int i = len - 1;
    		
    		if(!len) return s;
    		for(;i >= 0;i--)
    		{
    			result += s[i];
    		}
    		return result;
    
    	}
    }; 
    

     交换法:

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

      栈实现:

    class Solution {  
    public:  
        string reverseString(string s) {  
            string result ;  
            int len = s.length();  
            if(len==0) return result;  
            int i = 0;  
            stack<char> stk;  
            while(i< len)  
            {  
                stk.push(s[i]);  
                i++;  
            }  
            while(!stk.empty())  
            {  
                char temp = stk.top();  
                result.push_back(temp);  
                stk.pop();  
                  
            }  
            return result;  
        }  
    };  
    

      

  • 相关阅读:
    蚁群算法(AntColonyOptimization,ACO)与TSP问题
    EASY-X
    扩展欧几里得
    堆,set,优先队列
    单链表的几个基本操作
    剑指offer JZ-20
    剑指offer JZ-19
    拉普拉斯机制下的差分隐私(1)
    剑指offer JZ-17
    剑指offer JZ-16
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8405365.html
Copyright © 2020-2023  润新知