C\C++\Java Solution


  • 0
    L

    C:

    int mStrlen(const char * str)
    {
    	if (str == NULL || *str == '\0')
    	{
    		return 0;
    	}
    	else
    	{
    		return mStrlen(str + 1) + 1;
    	}
    }
    char* reverseString(char* s) {
    	int len = mStrlen(s);
    	int i;
    	char *temp = (char*)malloc(sizeof(char)*(len + 1));
    	for (i=0; i < len; i++)
    	{
    		 temp[i] = *(s + len - 1 - i);
    	}
    	temp[len] = '\0';
    	return temp;
    }
    

    C++:

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

    java:

    public class Solution {
        public String reverseString(String s) {
            char[] tempArr = s.toCharArray();
            for (int i = 0; i < tempArr.length / 2; i++)
            {
                char temp = tempArr[i];
                tempArr[i] = tempArr[tempArr.length -1 - i];
                tempArr[tempArr.length -1 - i] = temp;
            }
            return new String(tempArr);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.