简体   繁体   English

退货有什么问题?

[英]What's wrong with this return?

I'm new to not using a main method and i started leet coding in java and they give you the boilerplate code in a particular format. 我是不使用main方法的新手,我从Java中开始进行leet编码,它们以特定格式为您提供样板代码。 my logic is fine, but for some reason im not returning the proper string. 我的逻辑很好,但是由于某种原因,我没有返回正确的字符串。 can you guys help me on this one? 你们可以帮我吗?

class Solution {
    public String defangIPaddr(String address) {
        char[] newChar = new char[address.length()];
        address.getChars(0, address.length(), newChar, 0);

        for(int i = 0; i < address.length();i++) {
            if(newChar[i] == '.') {
                return "[.]";
            }else
                return Character.toString(newChar[i]);
        }
    }
}

For a given input 1.1.1.1 I want as output 1[.]1[.]1[.]1 . 对于给定的输入1.1.1.1我想要作为输出1[.]1[.]1[.]1

Based on the clarification in comments, instead of trying to replace each dot separately, use String#replaceAll method to replace them all at once. 根据注释中的说明,而不是尝试单独替换每个点,请使用String#replaceAll方法立即替换它们。

String address = "1.1.1.1";
address = address.replaceAll("\\.", "[.]"); //replace all dots
System.out.println(address); //prints 1[.]1[.]1[.]1

If you insist of doing the replacement yourself though, instead of messing with a bunch of indices, simply try to recreate the string from the start, appending each character to a StringBuilder , but if it is a dot append [.] 如果您坚持要自己替换,而不是弄乱一堆索引,只需尝试从头开始重新创建字符串,将每个字符附加到StringBuilder ,但是如果是点附加[.]

String address = "1.1.1.1";
StringBuilder sb = new StringBuilder();
for (char c : address.toCharArray()) {
    if (c == '.')
        sb.append("[.]");
    else
        sb.append(c);
}
address = sb.toString();
System.out.println(address); //prints 1[.]1[.]1[.]1

The logic is not good because it seems like you are returning the first character of the input string only. 逻辑不好,因为好像您仅返回输入字符串的第一个字符。 You can use a string builder for your solution or just a new string you will appending to. 您可以将字符串生成器用于您的解决方案,也可以仅使用要附加的新字符串。 Sample: 样品:

class Solution {
    public String defangIPaddr(String address) {
        char[] newChar = new char[address.length()];
        address.getChars(0, address.length(), newChar, 0);

        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < address.length();i++) {
            if(newChar[i] == '.') {
                sb.append("[.]"); //append to the string builder
            }else
                sb.append(Character.toString(newChar[i]));
        }

        return sb.toString(); //return the string then
    }
}

I hope this may help. 希望对您有所帮助。 Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM