【编程】【leetcode】344. Reverse String

本文详细探讨了字符编码之间的转换,包括Java和C++中的不同实现,并提供了多种字符串反转的方法,如利用内置函数、手动交换字符等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.字符编码

//字节和字符的区别    http://jiapumin.iteye.com/blog/1006144   getBytes和操作系统编码格式相关联的
import java.io.UnsupportedEncodingException;
public class Test01 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String gb=new String("中国".getBytes(),"gb2312");
        System.out.println(gb);
        String ios=new String(gb.getBytes("gb2312"),"ISO-8859-1");
        System.out.println(ios);  //原本编码格式转换成另外一种以后也是可能出现乱码的
        gb=new String(ios.getBytes("ISO-8859-1"),"gb2312");
        System.out.println(gb);

        //在IDEA中上面的中国都是乱码,只有在使用了utf-8以后才不是乱码  主要的原因在于ISO-8859-1没有对应的中文符号
        String gb2=new String("中国".getBytes(),"utf-8");
        System.out.println(gb2);
        String ios2=new String(gb2.getBytes("utf-8"),"ISO-8859-1");
        System.out.println(ios2);
        gb2=new String(ios2.getBytes("ISO-8859-1"),"utf-8");
        System.out.println(gb2);
    }
}

2.曾经项目中utf-b和ansi编码格式转换代码:

#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;

/*首先明确一点:ansi转utf8编码,不能直接相互转换,只能是经过unicode编码格式。*/

/*别人分解版本*/
string Unicode2Ascii(wstring wstrsrc);

wstring Ascii2Unicode(string astrsrc);

string Unicode2UTF8(wstring wstrsrc);

wstring UTF82Unicode(string utf8strsrc);


/*自己版本*/

string FromUtf8ToAnsi(const string& str)
{
	//从utf-8到unicode编码转换
	int len = 0;
	len = str.length();
	int  unicodeLen = ::MultiByteToWideChar(CP_UTF8,NULL,str.c_str(),-1,NULL,0 );
	wchar_t *  pUnicode;
	pUnicode = new  wchar_t[unicodeLen+1];
	memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
	::MultiByteToWideChar( CP_UTF8,NULL,str.c_str(),-1,(LPWSTR)pUnicode,unicodeLen );
	wstring  rt;
	rt = ( wchar_t* )pUnicode;
	delete  pUnicode;
	//return  rt;


	//从unicode到ansi编码转换
	char *pElementText;
	int iTextLen;
	iTextLen = WideCharToMultiByte( CP_ACP,NULL,rt.c_str(),-1,NULL,0,NULL,NULL );
	pElementText = new char[iTextLen + 1];
	memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );
	::WideCharToMultiByte( CP_ACP,0,rt.c_str(),-1,pElementText,iTextLen,NULL,NULL );
	string strText;
	strText = pElementText;
	delete[] pElementText;
	return strText;
}

//字符串从utf-8编码到ansi编码
string changestringencodingFromUtf8ToAnsi(const string& utf8str)
{
	string utf8str2 =utf8str;
	string ansistr ="";
	ansistr=FromUtf8ToAnsi(utf8str2);
	return ansistr;
}

string FromAnsitoUtf8(const string& ansistr)
{

	//ansi到unicode编码转换
	string ansistr2=ansistr;
	int sLen = MultiByteToWideChar(CP_ACP, NULL, ansistr2.c_str(), -1, NULL, 0);
	wchar_t* sUnicode = new wchar_t[sLen];
	//wchar_t* sUnicode = (wchar_t*)malloc(sLen*sizeof(wchar_t));
	MultiByteToWideChar(CP_ACP, NULL, ansistr2.c_str(), -1, sUnicode, sLen);
	//wstring  rt;
	//rt = ( wchar_t* )sUnicode;
	//delete  sUnicode;

	//从unicode编码到ansi编码转换
	//wchar_t *sUnicode = L"Convert Unicode to ANSI, Unicode 转换为 ANSI";
	int sLen2 = WideCharToMultiByte(CP_ACP, NULL, sUnicode, -1, NULL, 0, NULL, NULL);
	char* sAnsi = new char[sLen2];
	//char* sAnsi = (char*)malloc(sLen);
	WideCharToMultiByte(CP_ACP, NULL, sUnicode, -1, sAnsi, sLen2, NULL, NULL);
	string strText;
	strText = sAnsi;
	delete[] sAnsi;
	return strText;
}

//字符串从ansi编码到utf-8编码
string changestringencodingFromAnsiToUtf8(const string& ansistr)
{
	string ansistr2 =ansistr;
	string ansistr3 ="";
	ansistr3=FromAnsitoUtf8(ansistr2);
	return ansistr3;
}

int main(int argc, char* argv[])
{
	char szText[] = "这是一个ANSI转化为UTF8的例子!\r\n";
	wstring strUnicode;
	string strAnsi, strUTF8;
	strAnsi = szText;
	strUnicode = Ascii2Unicode(strAnsi);
	strUTF8 = Unicode2UTF8(strUnicode);
	cout << strUTF8 << endl;

	strUnicode = UTF82Unicode(strUTF8);
	strAnsi = Unicode2Ascii(strUnicode);
	cout << strAnsi << endl;

	/*char szText[] = "这是一个ANSI转化为UTF8的例子!\r\n";
	string strutf8="";
	string stransi="";
	strutf8=changestringencodingFromAnsiToUtf8(szText);
	cout<<strutf8<<endl;

	stransi=changestringencodingFromUtf8ToAnsi(strutf8);
	cout<<stransi<<endl;*/
	return 0;
}

string Unicode2Ascii(wstring wstrsrc)
{
	int nLength = ::WideCharToMultiByte(CP_OEMCP, 0, wstrsrc.c_str(), -1, NULL, 0, NULL, NULL);
	if(nLength <= 0) return string("");
	char *szbuffer = new char[nLength + 2];
	::WideCharToMultiByte(CP_OEMCP, 0, wstrsrc.c_str(), -1, szbuffer, nLength, NULL, NULL);
	string strnew = szbuffer;
	delete [] szbuffer;
	return strnew;
}
wstring Ascii2Unicode(string astrsrc)
{
	int nLength = ::MultiByteToWideChar(CP_ACP, 0, astrsrc.c_str(), -1, NULL, 0);
	if(nLength <= 0) return wstring(L"");
	wchar_t *szbuffer = new wchar_t[nLength + 2];
	::MultiByteToWideChar(CP_ACP, 0, astrsrc.c_str(), -1, szbuffer, nLength);
	wstring strnew = szbuffer;
	delete [] szbuffer;
	return strnew;
}
string Unicode2UTF8(wstring wstrsrc)
{
	int nLength = ::WideCharToMultiByte(CP_UTF8, 0, wstrsrc.c_str(), -1, NULL, 0, NULL, NULL);
	if(nLength <= 0) return string("");
	char *szbuffer = new char[nLength + 2];
	::WideCharToMultiByte(CP_UTF8, 0, wstrsrc.c_str(), -1, szbuffer, nLength, NULL, NULL);
	string strnew = szbuffer;
	delete [] szbuffer;
	return strnew;
}
wstring UTF82Unicode(string utf8strsrc)
{
	int nLength = ::MultiByteToWideChar(CP_UTF8, 0, utf8strsrc.c_str(), -1, NULL, 0);
	if(nLength <= 0) return wstring(L"");
	wchar_t *szbuffer = new wchar_t[nLength + 2];
	::MultiByteToWideChar(CP_UTF8, 0, utf8strsrc.c_str(), -1, szbuffer, nLength);
	wstring strnew = szbuffer;
	delete [] szbuffer;
	return strnew;
}


3.c++内置反转函数

#include <iostream>     // std::cout
#include <algorithm>    // std::reverse
#include <vector>       // std::vector

int main() {
	std::vector<int> myvector;

	// set some values:
	for (int i = 1; i < 10; ++i) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9

	std::reverse(myvector.begin(), myvector.end());    // 9 8 7 6 5 4 3 2 1

	// print out content:
	std::cout << "myvector contains:";
	for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
		std::cout << ' ' << *it;
	std::cout << '\n';
	return 0;
}
----------------------------------------------------------------------------------
// string::rbegin/rend
#include <iostream>
#include <string>

int main ()
{
  std::string str ("now step live...");
  for (std::string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit)
    std::cout << *rit;
  return 0;
}
---------------------------------------------------------------------------------
#include <iostream>
#include<String>
using namespace std;
int main(){
	string text="i am student!";
	text=string(text.rbegin(),text.rend());
	cout<<text<<endl;
	return 0;
}


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

2.
public class Solution {
    public String reverseString(String s) {
        byte[] bytes = s.getBytes();
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            byte temp = bytes[i];
            bytes[i] = bytes[j];
            bytes[j] = temp;
            i++;
            j--;
        }
        return new String(bytes);
    }
}


//异或操作运算符
3.
public class Solution {
    public String reverseString(String s) {
        char[] word = s.toCharArray();
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            word[i] = (char) (word[i] ^ word[j]);
            word[j] = (char) (word[i] ^ word[j]);
            word[i] = (char) (word[i] ^ word[j]);
            i++;
            j--;
        }
        return new String(bytes);
    }
}

4.
public class Solution {
    public String reverseString(String s) {
        byte[] bytes = s.getBytes();
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            bytes[i] = (byte) (bytes[i] ^ bytes[j]);
            bytes[j] = (byte) (bytes[i] ^ bytes[j]);
            bytes[i] = (byte) (bytes[i] ^ bytes[j]);
            i++;
            j--;
        }
        return new String(bytes);
    }
}


//Java library
5.
class Solution {
public:
    string reverseString(string s) {
        s=string(s.rbegin(),s.rend());
        return s;
    }
};

6.
public class Solution {
    public String reverseString(String s) {
        return new StringBuilder(s).reverse().toString();
    }
}


//分治 递归
7.
public class Solution {
    public String reverseString(String s) {
        int length = s.length();
        if (length <= 1) return s;
        String leftStr = s.substring(0, length / 2);
        String rightStr = s.substring(length / 2, length);
        return reverseString(rightStr) + reverseString(leftStr);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值