Алгоритм поиска палиндрома
Как написать алгоритм "который ищет полиндроми и подсчитывает их количество после чего записывает в файл txt" ?
Задали это сделать алгоритмично.(
Мой код
public class zad2Ver3 {
private static String pathToFile = "/Users/mk/Desktop/palindromy.txt";
private static String newPathToFile = "/Users/mk/Desktop/newPalindrom.txt";
public static void main(String[] args) throws Exception {
readTXT();
}
private static void readTXT() throws Exception {
List<String> strList = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(pathToFile))) {
String line;
while ((line = br.readLine()) != null) {
strList.add(line);
}
int count = 0;
for (int i = 0; i < strList.size(); i++) {
String str = strList.get(i);
char[] chr = new char[str.toCharArray().length];
if (wykladPalindrom(chr) == true) {
count++;
System.out.println(count);
}
}
} catch (FileNotFoundException e) {
System.err.println("File does not exist");
} catch (IOException e) {
System.err.println("File with path " + pathToFile + " not found");
}
}
public static boolean wykladPalindrom(char str[]) {
int i, j;
j = str.length;
for (i = 0; i < j; i++) {
if (str[i] != str[j - 1 - i])
return false;
}
return true;
}
}
Ответы (3 шт):
Автор решения: Igor
→ Ссылка
public static boolean isPalindrom(char str[]) {
int i, j;
for (i = 0, j = str.length - 1; str[i] == str[j] && i < j; i++, j--);
return i >= j;
}
if (wykladPalindrom(str.toCharArray())) {
Автор решения: Дмитрий
→ Ссылка
Вот вам еще 2 варианта, но начинайте делать задания самостоятельно. Если вы сдаетесь на таких тривиальных задачах, учитывая, что у вас есть преподаватель, который отвечает на любые вопросы и еще что-то предварительно объясняет, имея огромное количество материала в инете (включая уже решенные аналогичные задачи), то что будет в реальной разработке...
public static boolean isPslindrom1(String str) {
return new StringBuilder(str).reverse().toString().equals(str);
}
public static boolean isPslindrom2(String str) {
char[] temp = new char[str.length()];
for (int i = 0; i < str.length(); i++) temp[str.length() - i - 1] = str.charAt(i);
return new String (temp).equals(str);
}
Автор решения: Hotosho
→ Ссылка
Всем спасибо за помощь, я нашел ошибку в своем коде... почему не он не работал. Теперь работает) НО я знаю что мой способ самый не верный)
package algo4;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Zadanie2Polindrom {
private static String pathToFile = "/Users/mk/Desktop/palindromy.txt";
private static String newPathToFile = "/Users/mk/Desktop/newPalindrom.txt";
public static void main(String[] args) throws Exception {
readTXT();
}
private static void readTXT() throws Exception {
List<String> strList = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(pathToFile))) {
String line;
while ((line = br.readLine()) != null) {
strList.add(line);
}
int count = 0;
for (int i = 0; i < strList.size(); i++) {
String str = strList.get(i);
char[] chr = new char[str.length()];
for (int j = 0; j < str.length(); j++) {
chr[j] = str.charAt(j);
}
if (wykladPalindrom(chr) == true) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(newPathToFile, true))) {
bw.write(str + "\n");
} catch (IOException e) {
System.err.println(newPathToFile + " Can't write to file");
}
count++;
}
}
System.out.println(count);
} catch (FileNotFoundException e) {
System.err.println("File does not exist");
} catch (IOException e) {
System.err.println("File with path " + pathToFile + " not found");
}
}
public static boolean wykladPalindrom(char str[]) {
int i, j;
j = str.length;
for (i = 0; i < j; i++) {
if (str[i] != str[j - 1 - i])
return false;
}
return true;
}
}