The input is a string of digits. You must find the longest substring which first half digits sum is equal to the right half digits sum.
Input: String str = "45071198"; Output: 6 Explanation: The Longest Substring with the same first and second half sum is: “450711”. |
Solution:
1. static int findLongestLength(String input) { 2. int length = input.length(); 3. int answer = 0; 4. 5. for (int i = 0; i <= length - 2; i++) { 6. int left = i; 7. int right = i + 1; 8. 9. int leftSum = 0; 10. int rightSum = 0; 11. 12. while (right < length && left >= 0) { 13. leftSum += input.charAt(left) - '0'; 14. rightSum += input.charAt(right) - '0'; 15. if (leftSum == rightSum) { 16. answer = Math.max(answer, right - left + 1); 17. } 18. left--; 19. right++; 20. } 21. } 22. return answer; 23. } 24.
Comments