mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-24 04:54:21 +08:00
Change project structure to a Maven Java project + Refactor (#2816)
This commit is contained in:

committed by
GitHub

parent
8e533d2617
commit
9fb3364ccc
34
src/main/java/com/thealgorithms/strings/Alphabetical.java
Normal file
34
src/main/java/com/thealgorithms/strings/Alphabetical.java
Normal file
@ -0,0 +1,34 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
/**
|
||||
* Alphabetical order is a system whereby character strings are placed in order
|
||||
* based on the position of the characters in the conventional ordering of an
|
||||
* alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
|
||||
*/
|
||||
class Alphabetical {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert !isAlphabetical("123abc");
|
||||
assert isAlphabetical("aBC");
|
||||
assert isAlphabetical("abc");
|
||||
assert !isAlphabetical("xyzabc");
|
||||
assert isAlphabetical("abcxyz");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string is alphabetical order or not
|
||||
*
|
||||
* @param s a string
|
||||
* @return {@code true} if given string is alphabetical order, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
public static boolean isAlphabetical(String s) {
|
||||
s = s.toLowerCase();
|
||||
for (int i = 0; i < s.length() - 1; ++i) {
|
||||
if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
30
src/main/java/com/thealgorithms/strings/CharactersSame.java
Normal file
30
src/main/java/com/thealgorithms/strings/CharactersSame.java
Normal file
@ -0,0 +1,30 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
public class CharactersSame {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
assert isAllCharactersSame("");
|
||||
assert !isAllCharactersSame("aab");
|
||||
assert isAllCharactersSame("aaa");
|
||||
assert isAllCharactersSame("11111");
|
||||
}
|
||||
|
||||
/**
|
||||
* check if all the characters of a string are same
|
||||
*
|
||||
* @param s the string to check
|
||||
* @return {@code true} if all characters of a string are same, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
public static boolean isAllCharactersSame(String s) {
|
||||
for (int i = 1, length = s.length(); i < length; ++i) {
|
||||
if (s.charAt(i) != s.charAt(0)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
53
src/main/java/com/thealgorithms/strings/CheckAnagrams.java
Normal file
53
src/main/java/com/thealgorithms/strings/CheckAnagrams.java
Normal file
@ -0,0 +1,53 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Two strings are anagrams if they are made of the same letters arranged
|
||||
* differently (ignoring the case).
|
||||
*/
|
||||
public class CheckAnagrams {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert isAnagrams("Silent", "Listen");
|
||||
assert isAnagrams("This is a string", "Is this a string");
|
||||
assert !isAnagrams("There", "Their");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two strings are anagrams or not
|
||||
*
|
||||
* @param s1 the first string
|
||||
* @param s2 the second string
|
||||
* @return {@code true} if two string are anagrams, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isAnagrams(String s1, String s2) {
|
||||
int l1 = s1.length();
|
||||
int l2 = s2.length();
|
||||
s1 = s1.toLowerCase();
|
||||
s2 = s2.toLowerCase();
|
||||
Map<Character, Integer> charAppearances = new HashMap<>();
|
||||
|
||||
for (int i = 0; i < l1; i++) {
|
||||
char c = s1.charAt(i);
|
||||
int numOfAppearances = charAppearances.getOrDefault(c, 0);
|
||||
charAppearances.put(c, numOfAppearances + 1);
|
||||
}
|
||||
|
||||
for (int i = 0; i < l2; i++) {
|
||||
char c = s2.charAt(i);
|
||||
if (!charAppearances.containsKey(c)) {
|
||||
return false;
|
||||
}
|
||||
charAppearances.put(c, charAppearances.get(c) - 1);
|
||||
}
|
||||
|
||||
for (int cnt : charAppearances.values()) {
|
||||
if (cnt != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
53
src/main/java/com/thealgorithms/strings/CheckVowels.java
Normal file
53
src/main/java/com/thealgorithms/strings/CheckVowels.java
Normal file
@ -0,0 +1,53 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
/**
|
||||
* Vowel Count is a system whereby character strings are placed in order based
|
||||
* on the position of the characters in the conventional ordering of an
|
||||
* alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
|
||||
*/
|
||||
class CheckVowels {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert !hasVowels("This is a strings");
|
||||
assert hasVowels("Hello World");
|
||||
assert hasVowels("Java is fun");
|
||||
assert !hasVowels("123hi");
|
||||
assert hasVowels("Coding vs Programming");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string is has vowels or not
|
||||
*
|
||||
* @param input a string
|
||||
* @return {@code true} if given string has vowels, otherwise {@code false}
|
||||
*/
|
||||
public static boolean hasVowels(String input) {
|
||||
if (input.matches("[AEIOUaeiou]")) {
|
||||
countVowels(input);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* count the number of vowels
|
||||
*
|
||||
* @param input a string prints the count of vowels
|
||||
*/
|
||||
public static void countVowels(String input) {
|
||||
input = input.toLowerCase();
|
||||
int count = 0;
|
||||
int i = 0;
|
||||
while (i < input.length()) {
|
||||
if (input.charAt(i) == 'a'
|
||||
|| input.charAt(i) == 'e'
|
||||
|| input.charAt(i) == 'i'
|
||||
|| input.charAt(i) == 'o'
|
||||
|| input.charAt(i) == 'u') {
|
||||
count++;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
System.out.println(count);
|
||||
}
|
||||
}
|
183
src/main/java/com/thealgorithms/strings/HorspoolSearch.java
Normal file
183
src/main/java/com/thealgorithms/strings/HorspoolSearch.java
Normal file
@ -0,0 +1,183 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* This class is not thread safe<br>
|
||||
* <br>
|
||||
* (From wikipedia) In computer science, the Boyer–Moore–Horspool algorithm or
|
||||
* Horspool's algorithm is an algorithm for finding substrings in strings. It
|
||||
* was published by Nigel Horspool in 1980.
|
||||
* <br>
|
||||
* <a href=https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm>Wikipedia
|
||||
* page</a><br>
|
||||
* <br>
|
||||
*
|
||||
* <p>
|
||||
* An explanation:<br>
|
||||
*
|
||||
* <p>
|
||||
* The Horspool algorithm is a simplification of the Boyer-Moore algorithm in
|
||||
* that it uses only one of the two heuristic methods for increasing the number
|
||||
* of characters shifted when finding a bad match in the text. This method is
|
||||
* usually called the "bad symbol" or "bad character" shift. The bad symbol
|
||||
* shift method is classified as an input enhancement method in the theory of
|
||||
* algorithms. Input enhancement is (from wikipedia) the principle that
|
||||
* processing a given input to a problem and altering it in a specific way will
|
||||
* increase runtime efficiency or space efficiency, or both. Both algorithms try
|
||||
* to match the pattern and text comparing the pattern symbols to the text's
|
||||
* from right to left.<br>
|
||||
* <br>
|
||||
*
|
||||
* <p>
|
||||
* In the bad symbol shift method, a table is created prior to the search,
|
||||
* called the "bad symbol table". The bad symbol table contains the shift values
|
||||
* for any symbol in the text and pattern. For these symbols, the value is the
|
||||
* length of the pattern, if the symbol is not in the first (length - 1) of the
|
||||
* pattern. Else it is the distance from its rightmost occurrence in the pattern
|
||||
* to the last symbol of the pattern. In practice, we only calculate the values
|
||||
* for the ones that exist in the first (length - 1) of the pattern.<br>
|
||||
* <br>
|
||||
*
|
||||
* <p>
|
||||
* For more details on the algorithm and the more advanced Boyer-Moore I
|
||||
* recommend checking out the wikipedia page and professor Anany Levitin's book:
|
||||
* Introduction To The Design And Analysis Of Algorithms.
|
||||
*/
|
||||
public class HorspoolSearch {
|
||||
|
||||
private static HashMap<Character, Integer> shiftValues; // bad symbol table
|
||||
private static Integer patternLength;
|
||||
private static int comparisons = 0; // total comparisons in the current/last search
|
||||
|
||||
/**
|
||||
* Case sensitive version version of the algorithm
|
||||
*
|
||||
* @param pattern the pattern to be searched for (needle)
|
||||
* @param text the text being searched in (haystack)
|
||||
* @return -1 if not found or first index of the pattern in the text
|
||||
*/
|
||||
public static int findFirst(String pattern, String text) {
|
||||
return firstOccurrence(pattern, text, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Case insensitive version version of the algorithm
|
||||
*
|
||||
* @param pattern the pattern to be searched for (needle)
|
||||
* @param text the text being searched in (haystack)
|
||||
* @return -1 if not found or first index of the pattern in the text
|
||||
*/
|
||||
public static int findFirstInsensitive(String pattern, String text) {
|
||||
return firstOccurrence(pattern, text, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method that returns comparisons made by last run (mainly for
|
||||
* tests)
|
||||
*
|
||||
* @return number of character comparisons of the last search
|
||||
*/
|
||||
public static Integer getLastComparisons() {
|
||||
return HorspoolSearch.comparisons;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fairly standard implementation of the Horspool algorithm. Only the index
|
||||
* of the last character of the pattern on the text is saved and shifted by
|
||||
* the appropriate amount when a mismatch is found. The algorithm stops at
|
||||
* the first match or when the entire text has been exhausted.
|
||||
*
|
||||
* @param pattern String to be matched in the text
|
||||
* @param text text String
|
||||
* @return index of first occurrence of the pattern in the text
|
||||
*/
|
||||
private static int firstOccurrence(String pattern, String text, boolean caseSensitive) {
|
||||
shiftValues = calcShiftValues(pattern); // build the bad symbol table
|
||||
comparisons = 0; // reset comparisons
|
||||
|
||||
int textIndex
|
||||
= pattern.length() - 1; // align pattern with text start and get index of the last character
|
||||
|
||||
// while pattern is not out of text bounds
|
||||
while (textIndex < text.length()) {
|
||||
|
||||
// try to match pattern with current part of the text starting from last character
|
||||
int i = pattern.length() - 1;
|
||||
while (i >= 0) {
|
||||
comparisons++;
|
||||
char patternChar = pattern.charAt(i);
|
||||
char textChar = text.charAt((textIndex + i) - (pattern.length() - 1));
|
||||
if (!charEquals(patternChar, textChar, caseSensitive)) { // bad character, shift pattern
|
||||
textIndex += getShiftValue(text.charAt(textIndex));
|
||||
break;
|
||||
}
|
||||
i--;
|
||||
}
|
||||
|
||||
// check for full match
|
||||
if (i == -1) {
|
||||
return textIndex - pattern.length() + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// text exhausted, return failure
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares the argument characters
|
||||
*
|
||||
* @param c1 first character
|
||||
* @param c2 second character
|
||||
* @param caseSensitive boolean determining case sensitivity of comparison
|
||||
* @return truth value of the equality comparison
|
||||
*/
|
||||
private static boolean charEquals(char c1, char c2, boolean caseSensitive) {
|
||||
if (caseSensitive) {
|
||||
return c1 == c2;
|
||||
}
|
||||
return Character.toLowerCase(c1) == Character.toLowerCase(c2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the bad symbol table required to run the algorithm. The method
|
||||
* starts from the second to last character of the pattern and moves to the
|
||||
* left. When it meets a new character, it is by definition its rightmost
|
||||
* occurrence and therefore puts the distance from the current index to the
|
||||
* index of the last character into the table. If the character is already
|
||||
* in the table, then it is not a rightmost occurrence, so it continues.
|
||||
*
|
||||
* @param pattern basis for the bad symbol table
|
||||
* @return the bad symbol table
|
||||
*/
|
||||
private static HashMap<Character, Integer> calcShiftValues(String pattern) {
|
||||
patternLength = pattern.length();
|
||||
HashMap<Character, Integer> table = new HashMap<>();
|
||||
|
||||
for (int i = pattern.length() - 2;
|
||||
i >= 0;
|
||||
i--) { // length - 2 is the index of the second to last character
|
||||
char c = pattern.charAt(i);
|
||||
int finalI = i;
|
||||
table.computeIfAbsent(c, k -> pattern.length() - 1 - finalI);
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function that uses the bad symbol shift table to return the
|
||||
* appropriate shift value for a given character
|
||||
*
|
||||
* @param c character
|
||||
* @return shift value that corresponds to the character argument
|
||||
*/
|
||||
private static Integer getShiftValue(char c) {
|
||||
if (shiftValues.get(c) != null) {
|
||||
return shiftValues.get(c);
|
||||
} else {
|
||||
return patternLength;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class List_all_Possible_Words_From_Phone_Digits {
|
||||
|
||||
static Character[][] numberToCharMap;
|
||||
|
||||
private static List<String> printWords(int[] numbers,
|
||||
int len,
|
||||
int numIndex,
|
||||
String s) {
|
||||
if (len == numIndex) {
|
||||
return new ArrayList<>(Collections.singleton(s));
|
||||
}
|
||||
|
||||
List<String> stringList = new ArrayList<>();
|
||||
|
||||
for (int i = 0;
|
||||
i < numberToCharMap[numbers[numIndex]].length; i++) {
|
||||
String sCopy
|
||||
= String.copyValueOf(s.toCharArray());
|
||||
sCopy = sCopy.concat(
|
||||
numberToCharMap[numbers[numIndex]][i].toString());
|
||||
stringList.addAll(printWords(numbers, len,
|
||||
numIndex + 1,
|
||||
sCopy));
|
||||
}
|
||||
return stringList;
|
||||
}
|
||||
|
||||
private static void printWords(int[] numbers) {
|
||||
generateNumberToCharMap();
|
||||
List<String> stringList
|
||||
= printWords(numbers, numbers.length, 0, "");
|
||||
stringList.stream().forEach(System.out::println);
|
||||
}
|
||||
|
||||
private static void generateNumberToCharMap() {
|
||||
numberToCharMap = new Character[10][5];
|
||||
numberToCharMap[0] = new Character[]{'\0'};
|
||||
numberToCharMap[1] = new Character[]{'\0'};
|
||||
numberToCharMap[2] = new Character[]{'a', 'b', 'c'};
|
||||
numberToCharMap[3] = new Character[]{'d', 'e', 'f'};
|
||||
numberToCharMap[4] = new Character[]{'g', 'h', 'i'};
|
||||
numberToCharMap[5] = new Character[]{'j', 'k', 'l'};
|
||||
numberToCharMap[6] = new Character[]{'m', 'n', 'o'};
|
||||
numberToCharMap[7] = new Character[]{'p', 'q', 'r', 's'};
|
||||
numberToCharMap[8] = new Character[]{'t', 'u', 'v'};
|
||||
numberToCharMap[9] = new Character[]{'w', 'x', 'y', 'z'};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
public static void main(String[] args) {
|
||||
int number[] = {2, 3, 4};
|
||||
printWords(number);
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
// Longest Palindromic Substring
|
||||
import java.util.Scanner;
|
||||
|
||||
;
|
||||
|
||||
class LongestPalindromicSubstring {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Solution s = new Solution();
|
||||
String str = "";
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.print("Enter the string: ");
|
||||
str = sc.nextLine();
|
||||
System.out.println("Longest substring is : " + s.longestPalindrome(str));
|
||||
}
|
||||
}
|
||||
|
||||
class Solution {
|
||||
|
||||
public String longestPalindrome(String s) {
|
||||
if (s == null || s.length() == 0) {
|
||||
return "";
|
||||
}
|
||||
int n = s.length();
|
||||
String maxStr = "";
|
||||
for (int i = 0; i < n; ++i) {
|
||||
for (int j = i; j < n; ++j) {
|
||||
if (isValid(s, i, j) == true) {
|
||||
if (j - i + 1 > maxStr.length()) { // update maxStr
|
||||
maxStr = s.substring(i, j + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return maxStr;
|
||||
}
|
||||
|
||||
private boolean isValid(String s, int lo, int hi) {
|
||||
int n = hi - lo + 1;
|
||||
for (int i = 0; i < n / 2; ++i) {
|
||||
if (s.charAt(lo + i) != s.charAt(hi - i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
30
src/main/java/com/thealgorithms/strings/Lower.java
Normal file
30
src/main/java/com/thealgorithms/strings/Lower.java
Normal file
@ -0,0 +1,30 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
public class Lower {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
|
||||
for (String s : strings) {
|
||||
assert toLowerCase(s).equals(s.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts all of the characters in this {@code String} to lower case
|
||||
*
|
||||
* @param s the string to convert
|
||||
* @return the {@code String}, converted to lowercase.
|
||||
*/
|
||||
public static String toLowerCase(String s) {
|
||||
char[] values = s.toCharArray();
|
||||
for (int i = 0; i < values.length; ++i) {
|
||||
if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) {
|
||||
values[i] = Character.toLowerCase(values[i]);
|
||||
}
|
||||
}
|
||||
return new String(values);
|
||||
}
|
||||
}
|
71
src/main/java/com/thealgorithms/strings/Palindrome.java
Normal file
71
src/main/java/com/thealgorithms/strings/Palindrome.java
Normal file
@ -0,0 +1,71 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
/**
|
||||
* Wikipedia: https://en.wikipedia.org/wiki/Palindrome
|
||||
*/
|
||||
class Palindrome {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
String[] palindromes = {null, "", "aba", "123321"};
|
||||
for (String s : palindromes) {
|
||||
assert isPalindrome(s) && isPalindromeRecursion(s) && isPalindrome1(s);
|
||||
}
|
||||
|
||||
String[] notPalindromes = {"abb", "abc", "abc123"};
|
||||
for (String s : notPalindromes) {
|
||||
assert !isPalindrome(s) && !isPalindromeRecursion(s) && !isPalindrome1(s);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string is palindrome string or not
|
||||
*
|
||||
* @param s a string to check
|
||||
* @return {@code true} if given string is palindrome, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
public static boolean isPalindrome(String s) {
|
||||
return (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string is palindrome string or not using recursion
|
||||
*
|
||||
* @param s a string to check
|
||||
* @return {@code true} if given string is palindrome, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
public static boolean isPalindromeRecursion(String s) {
|
||||
if (s == null || s.length() <= 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (s.charAt(0) != s.charAt(s.length() - 1)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isPalindrome(s.substring(1, s.length() - 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string is palindrome string or not another way
|
||||
*
|
||||
* @param s a string to check
|
||||
* @return {@code true} if given string is palindrome, otherwise
|
||||
* {@code false}
|
||||
*/
|
||||
public static boolean isPalindrome1(String s) {
|
||||
if (s == null || s.length() <= 1) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
|
||||
if (s.charAt(i) != s.charAt(j)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
42
src/main/java/com/thealgorithms/strings/Pangram.java
Normal file
42
src/main/java/com/thealgorithms/strings/Pangram.java
Normal file
@ -0,0 +1,42 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
/**
|
||||
* Wikipedia: https://en.wikipedia.org/wiki/Pangram
|
||||
*/
|
||||
public class Pangram {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
assert isPangram("The quick brown fox jumps over the lazy dog");
|
||||
assert !isPangram("The quick brown fox jumps over the azy dog");
|
||||
/* not exists l character */
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string is a pangram string or not
|
||||
*
|
||||
* @param s string to check
|
||||
* @return {@code true} if given string is pangram, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isPangram(String s) {
|
||||
boolean[] marked = new boolean[26];
|
||||
/* by default all letters don't exists */
|
||||
char[] values = s.toCharArray();
|
||||
for (char value : values) {
|
||||
if (Character.isLetter(value)) {
|
||||
int index = Character.isUpperCase(value) ? value - 'A' : value - 'a';
|
||||
marked[index] = true;
|
||||
/* mark current character exists */
|
||||
}
|
||||
}
|
||||
|
||||
for (boolean b : marked) {
|
||||
if (!b) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
49
src/main/java/com/thealgorithms/strings/PermuteString.java
Normal file
49
src/main/java/com/thealgorithms/strings/PermuteString.java
Normal file
@ -0,0 +1,49 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
/*
|
||||
Backtracking algorithm used in the program:-
|
||||
|
||||
>>Fix a character in the first position and swap the rest of the character with the first character.
|
||||
Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A with
|
||||
A, B and C respectively.
|
||||
>>Repeat step 1 for the rest of the characters like fixing second character B and so on.
|
||||
>>Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B again,
|
||||
and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB.
|
||||
>>Repeat these steps for BAC and CBA, to get all the permutations.
|
||||
*/
|
||||
public class PermuteString {
|
||||
|
||||
//Function for swapping the characters at position I with character at position j
|
||||
public static String swapString(String a, int i, int j) {
|
||||
char[] b = a.toCharArray();
|
||||
char ch;
|
||||
ch = b[i];
|
||||
b[i] = b[j];
|
||||
b[j] = ch;
|
||||
return String.valueOf(b);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str = "ABC";
|
||||
int len = str.length();
|
||||
System.out.println("All the permutations of the string are: ");
|
||||
generatePermutation(str, 0, len);
|
||||
}
|
||||
|
||||
//Function for generating different permutations of the string
|
||||
public static void generatePermutation(String str, int start, int end) {
|
||||
//Prints the permutations
|
||||
if (start == end - 1) {
|
||||
System.out.println(str);
|
||||
} else {
|
||||
for (int i = start; i < end; i++) {
|
||||
//Swapping the string by fixing a character
|
||||
str = swapString(str, start, i);
|
||||
//Recursively calling function generatePermutation() for rest of the characters
|
||||
generatePermutation(str, start + 1, end);
|
||||
//Backtracking and swapping the characters again.
|
||||
str = swapString(str, start, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
43
src/main/java/com/thealgorithms/strings/ReverseString.java
Normal file
43
src/main/java/com/thealgorithms/strings/ReverseString.java
Normal file
@ -0,0 +1,43 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
/**
|
||||
* Reverse String using different version
|
||||
*/
|
||||
public class ReverseString {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert reverse("abc123").equals("321cba");
|
||||
assert reverse2("abc123").equals("321cba");
|
||||
}
|
||||
|
||||
/**
|
||||
* easiest way to reverses the string str and returns it
|
||||
*
|
||||
* @param str string to be reversed
|
||||
* @return reversed string
|
||||
*/
|
||||
public static String reverse(String str) {
|
||||
return new StringBuilder(str).reverse().toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* second way to reverses the string str and returns it
|
||||
*
|
||||
* @param str string to be reversed
|
||||
* @return reversed string
|
||||
*/
|
||||
public static String reverse2(String str) {
|
||||
|
||||
if (str == null || str.isEmpty()) {
|
||||
return str;
|
||||
}
|
||||
|
||||
char[] value = str.toCharArray();
|
||||
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
|
||||
char temp = value[i];
|
||||
value[i] = value[j];
|
||||
value[j] = temp;
|
||||
}
|
||||
return new String(value);
|
||||
}
|
||||
}
|
60
src/main/java/com/thealgorithms/strings/Rotation.java
Normal file
60
src/main/java/com/thealgorithms/strings/Rotation.java
Normal file
@ -0,0 +1,60 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
/**
|
||||
* Given a string, moving several characters in front of the string to the end
|
||||
* of the string. For example, move the two characters'a' and 'b' in front of
|
||||
* the string "abcdef" to the end of the string, so that the original string
|
||||
* becomes the string "cdefab"
|
||||
*/
|
||||
public class Rotation {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert rotation("abcdef", 2).equals("cdefab");
|
||||
|
||||
char[] values = "abcdef".toCharArray();
|
||||
rotation(values, 2);
|
||||
assert new String(values).equals("cdefab");
|
||||
}
|
||||
|
||||
/**
|
||||
* Move {@code n} characters in front of given string to the end of string
|
||||
* time complexity: O(n) space complexity: O(n)
|
||||
*
|
||||
* @param s given string
|
||||
* @param n the total characters to be moved
|
||||
* @return string after rotation
|
||||
*/
|
||||
public static String rotation(String s, int n) {
|
||||
return s.substring(n) + s.substring(0, n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move {@code n} characters in front of given character array to the end of
|
||||
* array time complexity: O(n) space complexity: O(1)
|
||||
*
|
||||
* @param values given character array
|
||||
* @param n the total characters to be moved
|
||||
*/
|
||||
public static void rotation(char[] values, int n) {
|
||||
reverse(values, 0, n - 1);
|
||||
reverse(values, n, values.length - 1);
|
||||
reverse(values, 0, values.length - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse character array
|
||||
*
|
||||
* @param values character array
|
||||
* @param from begin index of given array
|
||||
* @param to end index of given array
|
||||
*/
|
||||
public static void reverse(char[] values, int from, int to) {
|
||||
while (from < to) {
|
||||
char temp = values[from];
|
||||
values[from] = values[to];
|
||||
values[to] = temp;
|
||||
from++;
|
||||
to--;
|
||||
}
|
||||
}
|
||||
}
|
30
src/main/java/com/thealgorithms/strings/Upper.java
Normal file
30
src/main/java/com/thealgorithms/strings/Upper.java
Normal file
@ -0,0 +1,30 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
public class Upper {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
|
||||
for (String s : strings) {
|
||||
assert toUpperCase(s).equals(s.toUpperCase());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts all of the characters in this {@code String} to upper case
|
||||
*
|
||||
* @param s the string to convert
|
||||
* @return the {@code String}, converted to uppercase.
|
||||
*/
|
||||
public static String toUpperCase(String s) {
|
||||
char[] values = s.toCharArray();
|
||||
for (int i = 0; i < values.length; ++i) {
|
||||
if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) {
|
||||
values[i] = Character.toUpperCase(values[i]);
|
||||
}
|
||||
}
|
||||
return new String(values);
|
||||
}
|
||||
}
|
104
src/main/java/com/thealgorithms/strings/WordLadder.java
Normal file
104
src/main/java/com/thealgorithms/strings/WordLadder.java
Normal file
@ -0,0 +1,104 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.HashSet;
|
||||
|
||||
/*
|
||||
**Problem Statement:**
|
||||
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
|
||||
|
||||
Every adjacent pair of words differs by a single letter.
|
||||
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
|
||||
sk == endWord
|
||||
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
|
||||
|
||||
**Example 1:**
|
||||
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
|
||||
Output: 5
|
||||
Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
|
||||
|
||||
**Example 2:**
|
||||
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
|
||||
Output: 0
|
||||
Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
|
||||
|
||||
**Constraints:**
|
||||
1 <= beginWord.length <= 10
|
||||
endWord.length == beginWord.length
|
||||
1 <= wordList.length <= 5000
|
||||
wordList[i].length == beginWord.length
|
||||
beginWord, endWord, and wordList[i] consist of lowercase English letters.
|
||||
beginWord != endWord
|
||||
All the words in wordList are unique.
|
||||
*/
|
||||
class WordLadder {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
String beginWord = "hit";
|
||||
String endWord = "cog";
|
||||
String words[] = {"hot", "dot", "dog", "lot", "log", "cog"};
|
||||
List<String> wordList = Arrays.asList(words);
|
||||
|
||||
System.out.println("Ladder Length: " + ladderLength(beginWord, endWord, wordList));
|
||||
}
|
||||
|
||||
/**
|
||||
* This function finds the ladderLength
|
||||
*
|
||||
* @param beginWord: Starting word of the ladder
|
||||
* @param endWord: Ending word of the ladder
|
||||
* @param wordList: This list contains the words which needs to be included
|
||||
* in ladder.
|
||||
* @return ladderLength: This function will return the ladderLength(level)
|
||||
* if the endword is there. Otherwise, will return the length as 0.
|
||||
*/
|
||||
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
|
||||
HashSet<String> set = new HashSet();
|
||||
for (String word : wordList) {
|
||||
set.add(word);
|
||||
}
|
||||
|
||||
if (!set.contains(endWord)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
Queue<String> queue = new LinkedList();
|
||||
queue.offer(beginWord);
|
||||
int level = 1;
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
int size = queue.size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
String curr = queue.poll();
|
||||
char[] words_chars = curr.toCharArray();
|
||||
for (int j = 0; j < words_chars.length; j++) {
|
||||
char original_chars = words_chars[j];
|
||||
for (char c = 'a'; c <= 'z'; c++) {
|
||||
if (words_chars[j] == c) {
|
||||
continue;
|
||||
}
|
||||
words_chars[j] = c;
|
||||
String new_word = String.valueOf(words_chars);
|
||||
if (new_word.equals(endWord)) {
|
||||
return level + 1;
|
||||
}
|
||||
if (set.contains(new_word)) {
|
||||
set.remove(new_word);
|
||||
queue.offer(new_word);
|
||||
}
|
||||
}
|
||||
words_chars[j] = original_chars;
|
||||
}
|
||||
}
|
||||
level++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user