-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_29.java
More file actions
33 lines (27 loc) · 1021 Bytes
/
Problem_29.java
File metadata and controls
33 lines (27 loc) · 1021 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package strings;
// * Find the first repeated word in string.
public class Problem_29 {
public static String findFirstRepeatedWord(String str) {
if (str == null || str.isEmpty()) {
return null; // Empty string has no repeated words
}
int slow = 0, fast = 1;
while (fast < str.length() && slow < str.length()) {
if (str.charAt(slow) == str.charAt(fast)) {
return str.substring(slow, fast + 1); // Repeated word found
}
slow++;
fast += 2;
}
return null; // No repeated words found
}
public static void main(String[] args) {
String str = "This is a string with a repeated word this";
String firstRepeatedWord = findFirstRepeatedWord(str);
if (firstRepeatedWord != null) {
System.out.println("First repeated word: " + firstRepeatedWord);
} else {
System.out.println("No repeated words found in the string.");
}
}
}