步驟
- 輸入字符串
- 字符串轉(zhuǎn)換成字符串?dāng)?shù)組
- 數(shù)組轉(zhuǎn)換為List集合
- 將List集合轉(zhuǎn)化為Set集合(Set集合不允許重復(fù)值)
- Set集合轉(zhuǎn)換為數(shù)組 數(shù)組拼接成字符串
具體代碼實現(xiàn)如下:文章來源:http://www.zghlxwxcb.cn/news/detail-636806.html
public static String solution(String s){
StringBuffer sb = new StringBuffer(s);
String[] arr = new String[sb.length()];
// 將字符串轉(zhuǎn)換為字符串?dāng)?shù)組
for (int i = 0; i < sb.length(); i++) {
arr[i] = String.valueOf(sb.charAt(i));
}
// Arrays.asList(arr):將數(shù)組轉(zhuǎn)換為List集合形式
// 將arr的List集合輸入到set中用于去重
HashSet<String> set = new HashSet<String>(Arrays.asList(arr));
// 將set集合轉(zhuǎn)化成數(shù)組
String[] strarr = set.toArray(new String[0]);
// 數(shù)組拼接成字符串
String result = "";
for (int i = 0; i < strarr.length; i++) {
result = result + strarr[i];
}
return result;
}
其實原理很簡單,就是利用Set集合的特性來消除重復(fù)元素。文章來源地址http://www.zghlxwxcb.cn/news/detail-636806.html
到了這里,關(guān)于字符串去重(Java實現(xiàn))的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!