1576. 替换所有的问号

替换指定字符串中的’?’并且使不能有连续一样的字符
遍历的检测到’?’就检测前后位置替换字符

  1. public static String modifyString(String s) {
  2. StringBuilder sb = new StringBuilder();
  3. char[] ss = s.toCharArray();
  4. if (ss.length==1){
  5. if(ss[0]=='?'){
  6. return "a";
  7. }
  8. else return s;
  9. }
  10. for (int i = 0; i < ss.length; i++) {
  11. if (ss[i]=='?'){
  12. if (i != 0 && i != ss.length - 1) {
  13. char a = (char) (randomNumber(25) + 97);
  14. while(a==ss[i-1]||ss[i+1]==a) {
  15. a = (char) (randomNumber(25) + 97);
  16. }
  17. ss[i] = a;
  18. } else if (i==0){
  19. char a = (char) (randomNumber(25) + 97);
  20. while(ss[i+1]==a) {
  21. a = (char) (randomNumber(25) + 97);
  22. }
  23. ss[i] = a;
  24. } else if (i == ss.length - 1) {
  25. char a = (char) (randomNumber(25) + 97);
  26. while (a == ss[i - 1]) {
  27. a = (char) (randomNumber(25) + 97);
  28. }
  29. ss[i] = a;
  30. }
  31. }
  32. sb.append(ss[i]);
  33. }
  34. return sb.toString();
  35. }
  36. public static int randomNumber(int bound) {
  37. return (int) (Math.random() * 100000) % bound;
  38. }