Replace All ?’s to Avoid Consecutive Repeating Characters
给一个string, 其中有? 问怎么能替换?使得没有两个连续的字符.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Solution { public String modifyString(String s) { StringBuilder sb = new StringBuilder(s); for(int i = 0 ; i < sb.length(); i++) { if(sb.charAt(i) == '?'){ Set<Character> set = new HashSet<>(); if(i > 0) set.add(sb.charAt(i-1)); if(i < sb.length() - 1) set.add(sb.charAt(i+1)); for(char c = 'a'; c <= 'z'; c++) { if(!set.contains(c)){ sb.setCharAt(i, c); break; } } } } return sb.toString(); } } |