任何人都可以帮我纠正以下代码吗?

时间:2013-12-05 06:49:33

标签: java

请帮助我在此代码中识别我的错误。我是Java新手。如果我犯了任何错误,请原谅。这是codingbat java问题之一。我收到一些输入的Timed Out错误消息,如“xxxyakyyyakzzz”。对于像“yakpak”和“pakyak”这样的输入,这段代码工作正常。

问题: 假设字符串“yak”不吉利。给定一个字符串,返回一个删除所有“yak”的版本,但“a”可以是任何char。 “牦牛”字符串不会重叠。

 public String stringYak(String str) {
                String result = "";
                int yakIndex = str.indexOf("yak");
                if (yakIndex == -1) 
                    return str; //there is no yak
                //there is at least one yak
                //if there are yaks store their indexes in the arraylist
                ArrayList<Integer> yakArray = new ArrayList<Integer>();
                int length = str.length();
                yakIndex = 0;
                while (yakIndex < length - 3) {
                    yakIndex = str.indexOf("yak", yakIndex);
                    yakArray.add(yakIndex);
                    yakIndex += 3;
                }//all the yak indexes are stored in the arraylist
                //iterate through the arraylist. skip the yaks and get non-yak substrings
                for(int i = 0; i < length; i++) {
                    if (yakArray.contains(i)) 
                        i = i + 2;
                    else 
                        result = result + str.charAt(i);
                }
                return result;
 }

3 个答案:

答案 0 :(得分:0)

你不应该寻找以'y'开头并以'k'结尾的任何三个字符序列吗?像这样?

public static String stringYak(String str) {
  char[] chars = (str != null) ? str.toCharArray()
      : new char[] {};
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < chars.length; i++) {
    if (chars[i] == 'y' && chars[i + 2] == 'k') { // if we have 'y' and two away is 'k'
                                                  // then it's unlucky...
      i += 2;
      continue; //skip the statement sb.append 
    }           //do not append any pattern like y1k or yak etc
    sb.append(chars[i]);
  }
  return sb.toString();
}

public static void main(String[] args) {
  System.out.println(stringYak("1yik2yak3yuk4")); // Remove the "unlucky" strings
                                                  // The result will be 1234.
}

答案 1 :(得分:0)

看起来像你的编程任务。您需要使用正则表达式。

查看http://www.vogella.com/articles/JavaRegularExpressions/article.html#regex了解更多信息。 请记住,您不能使用contains。您的代码可能类似于

result = str.removeall("y\wk")

答案 2 :(得分:0)

您可以尝试

public static String stringYak(String str) {

    for (int i = 0; i < str.length(); i++) {
        if(str.charAt(i)=='y'){
            str=str.replace("yak", "");
        }
    }
    return str;
}
相关问题