Resolve build errors & cleanup structure (#2334)

This commit is contained in:
Andrii Siriak
2021-09-26 12:26:59 +03:00
committed by GitHub
parent 355900226a
commit dfe189b21f
48 changed files with 418 additions and 1102 deletions

33
Strings/Alphabetical.java Normal file
View File

@@ -0,0 +1,33 @@
package 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;
}
}

View File

@@ -0,0 +1,27 @@
package 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;
}
}

View File

@@ -0,0 +1,52 @@
package 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;
}
}

51
Strings/CheckVowels.java Normal file
View File

@@ -0,0 +1,51 @@
package 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);
}
}

172
Strings/HorspoolSearch.java Normal file
View File

@@ -0,0 +1,172 @@
package Strings;
import java.util.HashMap;
/**
* This class is not thread safe<br>
* <br>
* (From wikipedia) In computer science, the BoyerMooreHorspool 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;
}
}
}

28
Strings/Lower.java Normal file
View File

@@ -0,0 +1,28 @@
package 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);
}
}

64
Strings/Palindrome.java Normal file
View File

@@ -0,0 +1,64 @@
package 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;
}
}

35
Strings/Pangram.java Normal file
View File

@@ -0,0 +1,35 @@
package 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;
}
}

View File

@@ -0,0 +1,41 @@
package 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);
}
}

58
Strings/Rotation.java Normal file
View File

@@ -0,0 +1,58 @@
package 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--;
}
}
}

28
Strings/Upper.java Normal file
View File

@@ -0,0 +1,28 @@
package 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);
}
}