top of page
Caută
  • Poza scriitoruluioanaunciuleanu

Longest Even Length Substring such that the Sum of the First and Second Halves is the same in JAVA

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.

17 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no overlapping, in order to obtain the maximum profit. Solution: 1. static

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed vertically 2 x 1 or horizontally as 1 x 2. Solution: 1. static

bottom of page