去除字符串中的重复字符,对于出现超过2次(包含2次)的字符,只保留第一个。
例:输入abcbdde,输出abcde。
import java.util.*; public class Solution { /** * * @param str string字符串 * @return string字符串 */ public String removeDuplicatedChars (String str) { // write code here boolean[] isExistChar = new boolean[26]; boolean[] isExistNum = new boolean[10]; char[] chars = str.toCharArray(); StringBuilder sb = new StringBuilder(); for (char c : chars) { //是字母 if(c >= 'a' && c <= 'z'){ if(!isExistChar[c - 'a']){ sb.append(c); isExistChar[c - 'a'] = true; } } //是数字 if(c >= '0' && c <= '9'){ if(!isExistNum[c - '0']){ sb.append(c); isExistNum[c - '0'] = true; } } } return sb.toString(); } }
import java.util.*; public class Solution { /** * * @param str string字符串 * @return string字符串 */ public String removeDuplicatedChars (String str) { StringBuilder ansBuilder = new StringBuilder(); boolean[] flags = new boolean[128]; for (int i = 0, n = str.length(); i < n; i++) { char c = str.charAt(i); if (!flags[c]) { ansBuilder.append(c); flags[c] = true; } } return ansBuilder.toString(); } }
import java.util.*; public class Solution { /** * * @param str string字符串 * @return string字符串 */ public String removeDuplicatedChars (String str) { // write code here String newStr = ""; while (str.length() > 0) { newStr += String.valueOf(str.charAt(0)); str = str.replace(String.valueOf(str.charAt(0)), ""); } return newStr; } }
public static String duplicateRemoval(String str) { StringBuffer result = new StringBuffer(); char[] chars = str.toCharArray(); Set<Character> charSet = new HashSet<>(); for (char c : chars) { if (!charSet.contains(c)) { result.append(c); } charSet.add(c); } return result.toString(); }
public static String duplicateRemovalV2(String str) { if (StringUtils.isNotBlank(str)) { StringBuffer s = new StringBuffer(str); s = s.reverse(); str = s.toString(); str = str.replaceAll("(?s)(.)(?=.*\\1)", ""); s = new StringBuffer(str); return s.reverse().toString(); } return null; }