Instead of checking wordsChangeNotRepeat every time, wordsChangeNotRepeat can use HashSet :
StringBuilder sb = new StringBuilder(); Set<Character> set = new HashSet<>(); for (char c : str.toCharArray()) { if (!set.contains(c)) { sb.append(c); set.add(c); } } String result = sb.toString();
On small lines the difference will not be noticeable, however, for example, on a line of 10 million characters, the range of charcode-s of which is 1074, the difference is noticeable:
indexOf: 1180ms HashSet: 77ms
Since the resulting string is quite short, there are no advantages from using StringBuilder instead of resultString += c in terms of execution time, but in general it is recommended to use StringBuilder for such purposes.