有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

有人能用java给我解释一下这段代码的答案吗?

这就是问题所在

Given a string, return a version where all the "x" have been removed. Except an "x" at the very start or end should not be removed.

  • stringX("xxHxix")"xHix"
  • stringX("abxxxcd")"abcd"
  • stringX("xabxxxcdx")"xabcdx"

现在我理解了这个问题,但解决方案对我来说并不清楚,有人能解释一下吗

回答=

public String stringX(String str) {
  String result = "";
  for (int i=0; i<str.length(); i++) {
    // Only append the char if it is not the "x" case
    if (!(i > 0 && i < (str.length()-1) && str.substring(i, i+1).equals("x"))) {
      result = result + str.substring(i, i+1); // Could use str.charAt(i) here
    }
  }
  return result;
}

我的解决方案也是有效的,这个=

public String stringX(String str) {

  String ans = "";

  if(str.length() == 0) return ans;
  if(str.charAt(0) == 'x') ans += "x";

  for(int i = 0; i < str.length(); i++)
  {
    if(str.charAt(i) == 'x') continue;
    ans += (char) str.charAt(i);
  }

  if(str.charAt(str.length()-1) == 'x' && str.length() > 1) ans += "x";

  return ans;
}

共 (0) 个答案