這是我的解決方案,我可以確認作品。上面的那些實際上並不適合我 - 他們以某種方式給我編譯錯誤。我在InterviewStreet上得到了同樣的問題,提出了一個對9/15個測試用例有效的不完整的解決方案,因此我不得不花費更多的時間進行編碼。
這個想法不是關心如何獲得左和右的總和(這也是我最初做的),我會從給定輸入的每一半(左和右半)中得到所有可能的子串,將它們排序並附加到兩個單獨的列表中,然後查看是否有任何匹配。
爲什麼?
表示字符串「423」和「234」具有相同的總和;如果我對它們進行排序,它們都將是「234」並因此匹配。由於這些數字必須是連續的並且長度相等,我不再需要擔心必須將它們添加爲數字並進行檢查。
因此,舉例來說,如果我給12345678,然後在左側,for循環會給我:
[1,12,123,1234,2,23,234,3,34]
在右邊:
[5,56,567,5678,...]
等等。
但是,我只考慮了長度至少爲2的子字符串。
我附加每個這些子字符串,通過轉換排序爲一個字符數組,然後轉換回一個字符串到ArrayLists。
所以,現在所有這些都完成了,下一步是查看這兩個ArrayLists中是否有相同數字的相同字符串。我簡單地檢查每個temp_b的字符串對temp_a的第一個字符串,然後對temp_a的第二個字符串,等等。
如果我得到一個匹配(比如說「234」和「234」),我將這些匹配的子串的長度設置爲我的tempCount(tempCount = 3)。我還有另一個名爲'count'的變量來跟蹤這些匹配子字符串的最大長度(如果這是第一次匹配,則count = 0會被tempCount = 3覆蓋,所以count = 3)。
至於奇數/偶數字符串長度與變量int結尾,原因是因爲在代碼行s.length()/ 2 + j,是輸入長度碰巧是11,則:
s.length()= 11
s.length()/ 2 = 11/5 = 5.5 = 5
所以在for循環,s.length()/2 + j,其中j在s.length()/ 2處最大值將變爲:
5 + 5 = 10
其中缺少s.length(),我需要達到獲取字符串的最後一個索引。
這是因爲子串函數需要一個比你放入charAt(i)的東西更大的結束索引。
只是爲了演示, 「47582139875」 的輸入將產生以下輸出: [47,457,4578,24578,57,578,2578,58,258,28] < - 從左半 子串[139,1389,13789,135789,3793,789,35789,789,5789,578] < - 來自右半部分的子串-最長匹配的那個-'578'x的長度2
public static int getEqualSumSubtring(String s){
// run through all possible length combinations of the number string on left and right half
// append sorted versions of these into new ArrayList
ArrayList<String> temp_a = new ArrayList<String>();
ArrayList<String> temp_b = new ArrayList<String>();
int end; // s.length()/2 is an integer that rounds down if length is odd, account for this later
for(int i=0; i<=s.length()/2; i++){
for(int j=i; j<=s.length()/2; j++){
// only account for substrings with a length of 2 or greater
if(j-i > 1){
char[] tempArr1 = s.substring(i,j).toCharArray();
Arrays.sort(tempArr1);
String sorted1 = new String(tempArr1);
temp_a.add(sorted1);
//System.out.println(sorted1);
if(s.length() % 2 == 0)
end = s.length()/2+j;
else // odd length so we need the extra +1 at the end
end = s.length()/2+j+1;
char[] tempArr2 = s.substring(i+s.length()/2, end).toCharArray();
Arrays.sort(tempArr2);
String sorted2 = new String(tempArr2);
temp_b.add(sorted2);
//System.out.println(sorted2);
}
}
}
// For reference
System.out.println(temp_a);
System.out.println(temp_b);
// If the substrings match, it means they have the same sum
// Keep track of longest substring
int tempCount = 0 ;
int count = 0;
String longestSubstring = "";
for(int i=0; i<temp_a.size(); i++){
for(int j=0; j<temp_b.size(); j++){
if(temp_a.get(i).equals(temp_b.get(j))){
tempCount = temp_a.get(i).length();
if(tempCount > count){
count = tempCount;
longestSubstring = temp_a.get(i);
}
}
}
}
System.out.println(longestSubstring);
return count*2;
}
這是作業嗎? –
爲什麼代碼中有'48'?使用'0',它不會對人產生可怕的影響。 – INS
當它不工作,你怎麼知道它不工作? –