所以这里我有一个3200个字符的字符串我必须找到它们之间的空间最大的那对我已经有了找到该对的代码,但是我必须删除该对中的第一个字符并移动第二个字符串字符串的结尾并做这件事,直到它不可能这样做。这是我到目前为止所做的事情
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class StringPairs {
public static void main(String[] args) {
String inputString = readInputString();
printIdenticalSymbols(inputString);
}
private static String readInputString() {
Scanner in = new Scanner(System.in);
String inputString = in.nextLine();
in.close();
return inputString;
}
private static void printIdenticalSymbols(String inputString) {
Map<Character, Integer> symbolsMap = new HashMap<Character, Integer>();
char longestChar = ' ';
int longestDiff = -1;
int firstIndex = -1;
int lastIndex = -1;
int firstOccurenceOfLastIdentical = -1;
for (int i = 0; i < inputString.length(); i++) {
char currentCharacter = inputString.charAt(i);
if (!symbolsMap.containsKey(currentCharacter)) {
symbolsMap.put(currentCharacter, i);
continue;
}
int firstOccurenceIndex = symbolsMap.get(currentCharacter);
if (firstOccurenceIndex < firstOccurenceOfLastIdentical) {
symbolsMap.put(currentCharacter, i);
continue;
}
int currentIdenticalLength = i - firstOccurenceIndex;
if (currentIdenticalLength > longestDiff) {
longestChar = currentCharacter;
longestDiff = currentIdenticalLength;
firstIndex = firstOccurenceIndex;
lastIndex = i;
}
firstOccurenceOfLastIdentical = firstOccurenceIndex;
symbolsMap.put(currentCharacter, i);
}
System.out.println(longestChar + " - " + firstIndex + ":" + lastIndex);
}
}
示例输入:
brtba
输出:b:它们之间的空间(它已经这样做了)和rtab如果字符串更大就做这件事,直到它不可能这样做。
答案 0 :(得分:0)
我怀疑地看起来像是家庭作业。
无论如何,你应该研究String操作函数,尤其是String.substring(begin,end)。要进行循环,请查看while循环。请注意,您还没有处理没有配对的情况。
这就是说,我不明白测试的功能: (firstOccurenceIndex&lt; firstOccurenceOfLastIdentical)。