style: format code (#4212)

close #4204
This commit is contained in:
acbin
2023-06-09 18:52:05 +08:00
committed by GitHub
parent ad03086f54
commit 00282efd8b
521 changed files with 5233 additions and 7309 deletions

View File

@@ -25,10 +25,7 @@ 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

@@ -12,24 +12,21 @@ import java.util.HashMap;
*/
public class Anagrams {
// 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but differ in running time.
// 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*/
nm.approach2(first, second)); /* To activate methods for different approaches*/
System.out.println(
nm.approach1(first, second)
);/* To activate methods for different approaches*/
nm.approach1(first, second)); /* To activate methods for different approaches*/
System.out.println(
nm.approach3(first, second)
);/* To activate methods for different approaches*/
nm.approach3(first, second)); /* To activate methods for different approaches*/
System.out.println(
nm.approach4(first, second)
);/* To activate methods for different approaches*/
nm.approach4(first, second)); /* To activate methods for different approaches*/
/**
* OUTPUT :
* first string ="deal" second string ="lead"
@@ -55,9 +52,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 */
return Arrays.equals(c, d);
}
@@ -72,8 +69,10 @@ public class Anagrams {
for (char c : a.toCharArray()) {
m[c - 'a']++;
}
// In this approach the frequency of both the strings are stored and after that the frequencies are iterated from 0 to 26(from 'a' to 'z' ). If the frequencies match then anagram message is displayed in the form of boolean format
// Running time and space complexity of this algo is less as compared to others
// In this approach the frequency of both the strings are stored and after that the
// frequencies are iterated from 0 to 26(from 'a' to 'z' ). If the frequencies match
// then anagram message is displayed in the form of boolean format Running time and
// space complexity of this algo is less as compared to others
for (char c : b.toCharArray()) {
n[c - 'a']++;
}
@@ -90,7 +89,8 @@ public class Anagrams {
if (s.length() != t.length()) {
return false;
}
// this is similar to approach number 2 but here the string is not converted to character array
// this is similar to approach number 2 but here the string is not converted to character
// array
else {
int[] a = new int[26];
int[] b = new int[26];
@@ -110,7 +110,9 @@ public class Anagrams {
if (s.length() != t.length()) {
return false;
}
// This approach is done using hashmap where frequencies are stored and checked iteratively and if all the frequencies of first string match with the second string then anagram message is displayed in boolean format
// This approach is done using hashmap where frequencies are stored and checked iteratively
// and if all the frequencies of first string match with the second string then anagram
// message is displayed in boolean format
else {
HashMap<Character, Integer> nm = new HashMap<>();
HashMap<Character, Integer> kk = new HashMap<>();
@@ -126,22 +128,25 @@ public class Anagrams {
}
boolean approach5(String s, String t) {
if(s.length() != t.length()){
if (s.length() != t.length()) {
return false;
}
// Approach is different from above 4 aproaches.
// Here we initialize an array of size 26 where each element corresponds to the frequency of a character.
// Approach is different from above 4 aproaches.
// Here we initialize an array of size 26 where each element corresponds to the frequency of
// a character.
int[] freq = new int[26];
// iterate through both strings, incrementing the frequency of each character in the first string and decrementing the frequency of each character in the second string.
for(int i=0; i<s.length(); i++){
// iterate through both strings, incrementing the frequency of each character in the first
// string and decrementing the frequency of each character in the second string.
for (int i = 0; i < s.length(); i++) {
int pos1 = s.charAt(i) - 'a';
int pos2 = s.charAt(i) - 'a';
int pos2 = s.charAt(i) - 'a';
freq[pos1]++;
freq[pos2]--;
}
// iterate through the frequency array and check if all the elements are zero, if so return true else false
for(int i=0; i<26; i++){
if(freq[i] != 0){
// iterate through the frequency array and check if all the elements are zero, if so return
// true else false
for (int i = 0; i < 26; i++) {
if (freq[i] != 0) {
return false;
}
}

View File

@@ -11,9 +11,8 @@ import java.util.Set;
*/
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

@@ -1,7 +1,7 @@
package com.thealgorithms.strings;
/* In information theory, the Hamming distance between two strings of equal length
is the number of positions at which the corresponding symbols are different.
/* In information theory, the Hamming distance between two strings of equal length
is the number of positions at which the corresponding symbols are different.
https://en.wikipedia.org/wiki/Hamming_distance
*/
public class HammingDistance {
@@ -14,8 +14,7 @@ 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");
}

View File

@@ -92,11 +92,7 @@ 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
@@ -104,7 +100,8 @@ public class HorspoolSearch {
return -1;
}
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()) {
@@ -113,10 +110,9 @@ public class HorspoolSearch {
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
char textChar = text.charAt((textIndex + i) - (pattern.length() - 1));
if (!charEquals(
patternChar, textChar, caseSensitive)) { // bad character, shift pattern
textIndex += getShiftValue(text.charAt(textIndex));
break;
}
@@ -163,7 +159,8 @@ 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

@@ -15,8 +15,7 @@ public class LetterCombinationsOfPhoneNumber {
for (int i = 0; i < numberToCharMap[numbers[numIndex]].length; i++) {
String sCopy = String.copyValueOf(s.toCharArray());
sCopy =
sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString());
sCopy = sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString());
stringList.addAll(printWords(numbers, len, numIndex + 1, sCopy));
}
return stringList;
@@ -30,21 +29,21 @@ public class LetterCombinationsOfPhoneNumber {
protected 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
public static void main(String[] args) {
int[] number = { 2, 3, 4 };
int[] number = {2, 3, 4};
printWords(number);
}
}

View File

@@ -11,9 +11,7 @@ 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,10 +21,7 @@ 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

@@ -1,9 +1,10 @@
// Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). Here is my implementation
// Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer
// (similar to C/C++'s atoi function). Here is my implementation
package com.thealgorithms.strings;
public class MyAtoi {
public static int myAtoi(String s) {
public static int myAtoi(String s) {
s = s.trim();
char[] char_1 = s.toCharArray();
String number = "";
@@ -22,8 +23,7 @@ public static int myAtoi(String s) {
number = "0";
break;
}
if(ch >= '0' && ch <= '9')
number += ch;
if (ch >= '0' && ch <= '9') number += ch;
} else if (ch == '-' && !isDigit) {
number += "0";
negative = true;
@@ -40,15 +40,14 @@ public static int myAtoi(String s) {
break;
}
}
if (!isDigit) {
if (!isDigit) {
return 0;
}
number = number.replaceFirst("^0+(?!$)", "");
if (number.length() > 10 && negative) {
number = number.replaceFirst("^0+(?!$)", "");
if (number.length() > 10 && negative) {
return -2147483648;
} else if (number.length() > 10) {
return 2147483647;
@@ -64,9 +63,9 @@ public static int myAtoi(String s) {
}
}
if(negative){
return Integer.parseInt(number)*-1;
}
if (negative) {
return Integer.parseInt(number) * -1;
}
return Integer.parseInt(number);
}

View File

@@ -14,9 +14,7 @@ class Palindrome {
*/
public static boolean isPalindrome(String s) {
return (
(s == null || s.length() <= 1) ||
s.equals(new StringBuilder(s).reverse().toString())
);
(s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString()));
}
/**

View File

@@ -36,7 +36,7 @@ public class Pangram {
}
return true;
}
/**
* Checks if a String is Pangram or not by checking if each alhpabet is present or not
*

View File

@@ -7,13 +7,13 @@ Backtracking algorithm used in the program:-
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.
>>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
// 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

@@ -9,12 +9,11 @@ public class ReverseStringRecursive {
* @param str string to be reversed
* @return reversed string
*/
public static String reverse(String str)
{
if(str.isEmpty()){
public static String reverse(String str) {
if (str.isEmpty()) {
return str;
} else {
return reverse(str.substring(1))+str.charAt(0);
return reverse(str.substring(1)) + str.charAt(0);
}
}
}

View File

@@ -1,60 +1,62 @@
package com.thealgorithms.strings;
/* References : https://en.wikipedia.org/wiki/Run-length_encoding
* String compression algorithm deals with encoding the string, that is, shortening the size of the string
* String compression algorithm deals with encoding the string, that is, shortening the size of the
* string
* @author Swarga-codes (https://github.com/Swarga-codes)
*/
*/
public class StringCompression {
/**
* Returns the compressed or encoded string
*
* @param ch character array that contains the group of characters to be encoded
* @return the compressed character array as string
*/
public static String compress(String input) {
// Keeping the count as 1 since every element present will have atleast a count
// of 1
int count = 1;
String compressedString = "";
// Base condition to check whether the array is of size 1, if it is then we
// return the array
if (input.length() == 1) {
return "" + input.charAt(0);
}
// If the array has a length greater than 1 we move into this loop
for (int i = 0; i < input.length() - 1; i++) {
// here we check for similarity of the adjacent elements and change the count
// accordingly
if (input.charAt(i) == input.charAt(i + 1)) {
count = count + 1;
}
if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) {
compressedString = appendCount(compressedString, count, input.charAt(i));
break;
} else if (input.charAt(i) != input.charAt(i+1)) {
if ((i + 1) == input.length() - 1) {
compressedString = appendCount(compressedString, count, input.charAt(i)) + input.charAt(i+1);
break;
} else {
compressedString = appendCount(compressedString, count, input.charAt(i));
count = 1;
/**
* Returns the compressed or encoded string
*
* @param ch character array that contains the group of characters to be encoded
* @return the compressed character array as string
*/
public static String compress(String input) {
// Keeping the count as 1 since every element present will have atleast a count
// of 1
int count = 1;
String compressedString = "";
// Base condition to check whether the array is of size 1, if it is then we
// return the array
if (input.length() == 1) {
return "" + input.charAt(0);
}
}
// If the array has a length greater than 1 we move into this loop
for (int i = 0; i < input.length() - 1; i++) {
// here we check for similarity of the adjacent elements and change the count
// accordingly
if (input.charAt(i) == input.charAt(i + 1)) {
count = count + 1;
}
if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) {
compressedString = appendCount(compressedString, count, input.charAt(i));
break;
} else if (input.charAt(i) != input.charAt(i + 1)) {
if ((i + 1) == input.length() - 1) {
compressedString = appendCount(compressedString, count, input.charAt(i))
+ input.charAt(i + 1);
break;
} else {
compressedString = appendCount(compressedString, count, input.charAt(i));
count = 1;
}
}
}
return compressedString;
}
return compressedString;
}
/**
* @param res the resulting string
* @param count current count
* @param ch the character at a particular index
* @return the res string appended with the count
*/
public static String appendCount(String res, int count, char ch) {
if (count > 1) {
res += ch + "" + count;
count = 1;
} else {
res += ch + "";
/**
* @param res the resulting string
* @param count current count
* @param ch the character at a particular index
* @return the res string appended with the count
*/
public static String appendCount(String res, int count, char ch) {
if (count > 1) {
res += ch + "" + count;
count = 1;
} else {
res += ch + "";
}
return res;
}
return res;
}
}

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,10 +24,7 @@ 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,33 +1,31 @@
package com.thealgorithms.strings;
// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// An input string is valid if:
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
// Every close bracket has a corresponding open bracket of the same type.
// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine
// if the input string is valid. An input string is valid if: Open brackets must be closed by
// the same type of brackets. Open brackets must be closed in the correct order. Every close
// bracket has a corresponding open bracket of the same type.
public class ValidParentheses {
public static boolean isValid(String s) {
char[] stack = new char[s.length()];
int head = 0;
for(char c : s.toCharArray()) {
switch(c) {
case '{':
case '[':
case '(':
stack[head++] = c;
break;
case '}':
if(head == 0 || stack[--head] != '{') return false;
break;
case ')':
if(head == 0 || stack[--head] != '(') return false;
break;
case ']':
if(head == 0 || stack[--head] != '[') return false;
break;
}
}
return head == 0;
}
public static boolean isValid(String s) {
char[] stack = new char[s.length()];
int head = 0;
for (char c : s.toCharArray()) {
switch (c) {
case '{':
case '[':
case '(':
stack[head++] = c;
break;
case '}':
if (head == 0 || stack[--head] != '{') return false;
break;
case ')':
if (head == 0 || stack[--head] != '(') return false;
break;
case ']':
if (head == 0 || stack[--head] != '[') return false;
break;
}
}
return head == 0;
}
}

View File

@@ -8,22 +8,26 @@ import java.util.Queue;
/*
**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:
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.
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.
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.
Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation
sequence.
**Constraints:**
1 <= beginWord.length <= 10

View File

@@ -14,7 +14,8 @@ class longestNonRepeativeSubstring {
// adding key to map if not present
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();

View File

@@ -7,14 +7,16 @@ class zigZagPattern {
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);
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) {
if (height_space == 0)
pointer += depth_space;
else if (depth_space == 0)
pointer += height_space;
else if (bool) {
pointer += depth_space;
bool = false;
} else {