Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class Sentence implements Iterable<String> {
- private String s;
- Sentence(String s) {
- this.s = s;
- }
- @Override
- public Iterator<String> iterator() {
- return new PalindromeIterator();
- }
- @Override
- public String toString() {
- return s;
- }
- private class PalindromeIterator implements Iterator<String> {
- private int pos;
- PalindromeIterator() {
- pos = 0;
- }
- @Override
- public boolean hasNext() {
- while (true) {
- while (pos < s.length() && s.charAt(pos) == ' ') {
- pos++;
- }
- if (pos == s.length()) {
- return false;
- }
- int i = pos, j = 0;
- while (i < s.length() && s.charAt(i) != ' ') {
- i++;
- }
- i--;
- while (pos + j < i - j && s.charAt(pos + j) == s.charAt(i - j)) {
- j++;
- }
- if (pos + j >= i - j) {
- return true;
- } else {
- pos = i + 2;
- }
- }
- }
- @Override
- public String next() {
- while (true) {
- while (pos < s.length() && s.charAt(pos) == ' ') {
- pos++;
- }
- if (pos == s.length()) {
- throw new NoSuchElementException();
- }
- int i = pos, j = 0;
- while (i < s.length() && s.charAt(i) != ' ') {
- i++;
- }
- i--;
- while (j * 2 < i - pos && s.charAt(pos + j) == s.charAt(i - j)) {
- j++;
- }
- j = pos;
- pos = i + 2;
- if (pos + j >= i - j) {
- return s.substring(j, i + 1);
- }
- }
- }
- }
- }
- public class Test {
- public static void main(String[] args) {
- Sentence s = new Sentence("hello world x abcdcba 1232321 1243421 11 ");
- System.out.println("Предложение: " + s);
- System.out.print("Палиндромы:");
- for (String palindrome : s) {
- System.out.print(" " + palindrome);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement