0

我需要将一系列字符放在括号中的字符串中,这样它会选择最长的子字符串作为放在括号中的最佳字符串。说清楚,因为用文字解释太复杂了:如果我的输入是:

'these are some chars *£&$'
'these are some chars *£&$^%(((£'

两个输入的输出分别应该是:

'these are some chars (*£&$)'
'these are some chars (*£&$^%)(((£'

所以我想把序列 *£&$^% 如果它存在的话放在括号里,否则放在括号里 *£&$ 我希望它有意义!

4

2 回答 2

2

在一般情况下,此方法有效。它围绕任何给定字符串中任何关键字的最早子字符串:

public String bracketize() {
    String chars = ...; // you can put whatever input (such as 'these are some chars *£&$')
        String keyword = ...; // you can put whatever keyword (such as *£&$^%)
        String longest = "";
        for(int i=0;i<keyword.length()-1;i++) {
            for(int j=keyword.length(); j>i; j--) {
                String tempString = keyword.substring(i,j);
                if(chars.indexOf(tempString) != -1 && tempString.length()>longest.length()) {
                    longest = tempString;
                }
            }
        }
       if(longest.length() == 0)
           return chars; // no possible substring of keyword exists in chars, so just return chars
       String bracketized = chars.substring(0,chars.indexOf(longest))+"("+longest+")"+chars.substring(chars.indexOf(longest)+longest.length());
       return bracketized;
}

嵌套for循环检查每个可能的子字符串,并选择较大的,keyword中包含的最长的子字符串。例如,如果关键字是 Dog,它将检查子字符串“Dog”、“Do”、“D”、“og”、“o”和“g”。它将这个可能最长的子字符串存储在(初始化为空字符串)中。如果检查完每个子串的长度仍然为0,则在 中找不到这样的子串,所以返回原来的字符串chars。否则,返回一个新字符串,其子字符串用方括号(圆括号)括起来。Stringcharslongestlongestkeywordcharscharslongest

希望这会有所帮助,让我知道它是否有效。

于 2013-10-25T19:26:29.877 回答
1

尝试这样的事情(假设目标字符串只出现一次)。

String input = "these are some chars *£&$"
String output = "";
String[] split;

if(input.indexOf("*£&$^%")!=(-1)){
     split = input.split("*£&$^%");
     output = split[0]+"(*£&$^%)";
     if(split.length>1){
          output = output+split[1];
     }
}else if(input.indexOf("*£&$")!=(-1)){
     split = input.split("*£&$");
     output = split[0]+"(*£&$)";
     if(split.length>1){
         output = output+split[1];
     }
}else{
     System.out.println("does not contain either string");
}
于 2013-10-25T19:04:10.683 回答