Format code with prettier (#3375)

This commit is contained in:
acbin
2022-10-03 17:23:00 +08:00
committed by GitHub
parent 32b9b11ed5
commit e96f567bfc
464 changed files with 11483 additions and 6189 deletions

View File

@ -25,7 +25,10 @@ class Alphabetical {
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))) {
if (
!Character.isLetter(s.charAt(i)) ||
!(s.charAt(i) <= s.charAt(i + 1))
) {
return false;
}
}

View File

@ -3,7 +3,6 @@ package com.thealgorithms.strings;
import java.util.Arrays;
import java.util.HashMap;
/**
* An anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
* typically using all the original letters exactly once.[1]
@ -12,17 +11,25 @@ import java.util.HashMap;
* Reference from https://en.wikipedia.org/wiki/Anagram
*/
public class Anagrams {
// 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but differ in running time.
public static void main(String[] args) {
String first = "deal";
String second = "lead";
// All the below methods takes input but doesn't return any output to the main method.
Anagrams nm = new Anagrams();
System.out.println(nm.approach2(first, second)); /* To activate methods for different approaches*/
System.out.println(nm.approach1(first, second)); /* To activate methods for different approaches*/
System.out.println(nm.approach3(first, second)); /* To activate methods for different approaches*/
System.out.println(nm.approach4(first, second)); /* To activate methods for different approaches*/
System.out.println(
nm.approach2(first, second)
);/* To activate methods for different approaches*/
System.out.println(
nm.approach1(first, second)
);/* To activate methods for different approaches*/
System.out.println(
nm.approach3(first, second)
);/* To activate methods for different approaches*/
System.out.println(
nm.approach4(first, second)
);/* To activate methods for different approaches*/
/**
* OUTPUT :
* first string ="deal" second string ="lead"
@ -46,7 +53,9 @@ public class Anagrams {
char c[] = s.toCharArray();
char d[] = t.toCharArray();
Arrays.sort(c);
Arrays.sort(d); /* In this approach the strings are stored in the character arrays and both the arrays are sorted. After that both the arrays are compared for checking anangram */
Arrays.sort(
d
);/* In this approach the strings are stored in the character arrays and both the arrays are sorted. After that both the arrays are compared for checking anangram */
if (Arrays.equals(c, d)) {
return true;
} else {
@ -92,8 +101,7 @@ public class Anagrams {
b[t.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (a[i] != b[i])
return false;
if (a[i] != b[i]) return false;
}
return true;
}
@ -111,7 +119,6 @@ public class Anagrams {
nm.put(c, nm.getOrDefault(c, 0) + 1);
}
for (char c : t.toCharArray()) {
kk.put(c, kk.getOrDefault(c, 0) + 1);
}
// It checks for equal frequencies

View File

@ -10,7 +10,10 @@ import java.util.Set;
* alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
*/
public class CheckVowels {
private static final Set<Character> VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
private static final Set<Character> VOWELS = new HashSet<>(
Arrays.asList('a', 'e', 'i', 'o', 'u')
);
/**
* Check if a string is has vowels or not

View File

@ -14,14 +14,15 @@ public class HammingDistance {
* @return {@code int} hamming distance
* @throws Exception
*/
public static int calculateHammingDistance(String s1, String s2) throws Exception {
public static int calculateHammingDistance(String s1, String s2)
throws Exception {
if (s1.length() != s2.length()) {
throw new Exception("String lengths must be equal");
}
int stringLength = s1.length();
int counter = 0;
for (int i = 0; i < stringLength; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
counter++;

View File

@ -92,22 +92,26 @@ public class HorspoolSearch {
* @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) {
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
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));
char textChar = text.charAt(
(textIndex + i) - (pattern.length() - 1)
);
if (!charEquals(patternChar, textChar, caseSensitive)) { // bad character, shift pattern
textIndex += getShiftValue(text.charAt(textIndex));
break;
@ -155,9 +159,7 @@ public class HorspoolSearch {
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
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);

View File

@ -1,33 +1,34 @@
package com.thealgorithms.strings;
import java.util.*;
public class Isomorphic {
public static boolean checkStrings(String s, String t) {
if(s.length() != t.length()){
return false;
}
// To mark the characters of string using MAP
// character of first string as KEY and another as VALUE
// now check occurence by keeping the track with SET data structure
Map<Character, Character> characterMap = new HashMap<Character, Character>();
Set<Character> trackUinqueCharacter = new HashSet<Character>();
for(int i=0; i<s.length(); i++){
if(characterMap.containsKey(s.charAt(i))){
if(t.charAt(i) != characterMap.get(s.charAt(i))){
return false;
}
public static boolean checkStrings(String s, String t) {
if (s.length() != t.length()) {
return false;
}
else{
if(trackUinqueCharacter.contains(t.charAt(i))){
return false;
// To mark the characters of string using MAP
// character of first string as KEY and another as VALUE
// now check occurence by keeping the track with SET data structure
Map<Character, Character> characterMap = new HashMap<Character, Character>();
Set<Character> trackUinqueCharacter = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (characterMap.containsKey(s.charAt(i))) {
if (t.charAt(i) != characterMap.get(s.charAt(i))) {
return false;
}
} else {
if (trackUinqueCharacter.contains(t.charAt(i))) {
return false;
}
characterMap.put(s.charAt(i), t.charAt(i));
}
characterMap.put(s.charAt(i), t.charAt(i));
trackUinqueCharacter.add(t.charAt(i));
}
trackUinqueCharacter.add(t.charAt(i));
return true;
}
return true;
}
}

View File

@ -6,53 +6,50 @@ 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) {
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));
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, "");
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'};
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
// Driver code
public static void main(String[] args) {
int number[] = {2, 3, 4};
int number[] = { 2, 3, 4 };
printWords(number);
}
}

View File

@ -11,7 +11,9 @@ class LongestPalindromicSubstring {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string: ");
str = sc.nextLine();
System.out.println("Longest substring is : " + s.longestPalindrome(str));
System.out.println(
"Longest substring is : " + s.longestPalindrome(str)
);
}
}

View File

@ -6,7 +6,7 @@ public class Lower {
* Driver Code
*/
public static void main(String[] args) {
String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
String[] strings = { "ABC", "ABC123", "abcABC", "abc123ABC" };
for (String s : strings) {
assert toLowerCase(s).equals(s.toLowerCase());
}
@ -21,7 +21,10 @@ public class Lower {
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])) {
if (
Character.isLetter(values[i]) &&
Character.isUpperCase(values[i])
) {
values[i] = Character.toLowerCase(values[i]);
}
}

View File

@ -9,14 +9,18 @@ class Palindrome {
* Driver Code
*/
public static void main(String[] args) {
String[] palindromes = {null, "", "aba", "123321"};
String[] palindromes = { null, "", "aba", "123321" };
for (String s : palindromes) {
assert isPalindrome(s) && isPalindromeRecursion(s) && isPalindrome1(s);
assert isPalindrome(s) &&
isPalindromeRecursion(s) &&
isPalindrome1(s);
}
String[] notPalindromes = {"abb", "abc", "abc123"};
String[] notPalindromes = { "abb", "abc", "abc123" };
for (String s : notPalindromes) {
assert !isPalindrome(s) && !isPalindromeRecursion(s) && !isPalindrome1(s);
assert !isPalindrome(s) &&
!isPalindromeRecursion(s) &&
!isPalindrome1(s);
}
}
@ -28,7 +32,10 @@ class Palindrome {
* {@code false}
*/
public static boolean isPalindrome(String s) {
return (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString());
return (
(s == null || s.length() <= 1) ||
s.equals(new StringBuilder(s).reverse().toString())
);
}
/**

View File

@ -13,7 +13,7 @@ Backtracking algorithm used in the program:-
*/
public class PermuteString {
//Function for swapping the characters at position I with character at position j
//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;
@ -30,18 +30,18 @@ public class PermuteString {
generatePermutation(str, 0, len);
}
//Function for generating different permutations of the string
//Function for generating different permutations of the string
public static void generatePermutation(String str, int start, int end) {
//Prints the permutations
//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
//Swapping the string by fixing a character
str = swapString(str, start, i);
//Recursively calling function generatePermutation() for rest of the characters
//Recursively calling function generatePermutation() for rest of the characters
generatePermutation(str, start + 1, end);
//Backtracking and swapping the characters again.
//Backtracking and swapping the characters again.
str = swapString(str, start, i);
}
}

View File

@ -27,7 +27,6 @@ public class ReverseString {
* @return reversed string
*/
public static String reverse2(String str) {
if (str == null || str.isEmpty()) {
return str;
}

View File

@ -6,7 +6,7 @@ public class Upper {
* Driver Code
*/
public static void main(String[] args) {
String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
String[] strings = { "ABC", "ABC123", "abcABC", "abc123ABC" };
for (String s : strings) {
assert toUpperCase(s).equals(s.toUpperCase());
}
@ -24,7 +24,10 @@ public class Upper {
}
char[] values = s.toCharArray();
for (int i = 0; i < values.length; ++i) {
if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) {
if (
Character.isLetter(values[i]) &&
Character.isLowerCase(values[i])
) {
values[i] = Character.toUpperCase(values[i]);
}
}

View File

@ -1,10 +1,10 @@
package com.thealgorithms.strings;
import java.util.List;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/*
**Problem Statement:**
@ -40,13 +40,14 @@ class WordLadder {
* Driver Code
*/
public static void main(String[] args) {
String beginWord = "hit";
String endWord = "cog";
String words[] = {"hot", "dot", "dog", "lot", "log", "cog"};
String words[] = { "hot", "dot", "dog", "lot", "log", "cog" };
List<String> wordList = Arrays.asList(words);
System.out.println("Ladder Length: " + ladderLength(beginWord, endWord, wordList));
System.out.println(
"Ladder Length: " + ladderLength(beginWord, endWord, wordList)
);
}
/**
@ -59,7 +60,11 @@ class WordLadder {
* @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) {
public static int ladderLength(
String beginWord,
String endWord,
List<String> wordList
) {
HashSet<String> set = new HashSet();
for (String word : wordList) {
set.add(word);

View File

@ -1,47 +1,40 @@
package com.thealgorithms.strings ;
import java.util.HashMap ;
package com.thealgorithms.strings;
import java.util.HashMap;
class longestNonRepeativeSubstring {
public static int lengthOfLongestSubstring(String s) {
int max = 0 , start = 0 , i = 0 ;
HashMap< Character , Integer > map = new HashMap<>() ;
while ( i < s.length() ) {
int max = 0, start = 0, i = 0;
HashMap<Character, Integer> map = new HashMap<>();
char temp = s.charAt( i ) ;
while (i < s.length()) {
char temp = s.charAt(i);
// adding key to map if not present
if ( ! map.containsKey( temp ) )
map.put( temp , 0 ) ;
if (!map.containsKey(temp)) map.put(temp, 0);
// checking if the first value is the dublicate value
else if ( s.charAt( start ) == temp )
start++ ;
else if (s.charAt(start) == temp) start++;
// checking if the previous value is dublicate value
else if ( s.charAt( i - 1 ) == temp ) {
if ( max < map.size() ) max = map.size() ;
map = new HashMap<>() ;
start = i ;
i-- ;
else if (s.charAt(i - 1) == temp) {
if (max < map.size()) max = map.size();
map = new HashMap<>();
start = i;
i--;
}
// last possible place where dublicate value can be is between start and i
else {
if ( max < map.size() ) max = map.size() ;
while ( s.charAt( start ) != temp ) {
map.remove( s.charAt( start ) ) ;
start++ ;
if (max < map.size()) max = map.size();
while (s.charAt(start) != temp) {
map.remove(s.charAt(start));
start++;
}
start++ ;
start++;
}
i++ ;
i++;
}
if ( max < map.size() ) max = map.size() ;
return max ;
if (max < map.size()) max = map.size();
return max;
}
}

View File

@ -1,30 +1,31 @@
package com.thealgorithms.strings.zigZagPattern;
class zigZagPattern {
public static String encode(String s, int numRows) {
if ( numRows < 2 || s.length() < numRows ) return s ;
int start = 0 , index = 0 , height = 1 , depth = numRows ;
char[] zigZagedArray = new char[ s.length() ] ;
while ( depth != 0 ) {
int pointer = start , height_space = 2 + ( ( height - 2 ) * 2 ) , depth_space = 2 + ( ( depth - 2 ) * 2 ) ;
boolean bool = true ;
while ( pointer < s.length() ) {
zigZagedArray[index++] = s.charAt( pointer ) ;
if ( height_space == 0 ) pointer += depth_space ;
else if ( depth_space == 0 ) pointer += height_space ;
else if ( bool ) {
pointer += depth_space ;
bool = false ;
if (numRows < 2 || s.length() < numRows) return s;
int start = 0, index = 0, height = 1, depth = numRows;
char[] zigZagedArray = new char[s.length()];
while (depth != 0) {
int pointer = start, height_space =
2 + ((height - 2) * 2), depth_space = 2 + ((depth - 2) * 2);
boolean bool = true;
while (pointer < s.length()) {
zigZagedArray[index++] = s.charAt(pointer);
if (height_space == 0) pointer += depth_space; else if (
depth_space == 0
) pointer += height_space; else if (bool) {
pointer += depth_space;
bool = false;
} else {
pointer += height_space ;
bool = true ;
pointer += height_space;
bool = true;
}
}
height++ ;
depth-- ;
start++ ;
height++;
depth--;
start++;
}
return new String( zigZagedArray ) ;
return new String(zigZagedArray);
}
}
}