Skip to content

feat: Added string symmetry check algorithm #1461

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions String/CheckMirrorString.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* @function checkMirrorString
* @description Given a string check whether string is symmetric or not or (reflection in a mirror)
* @param {String} inputString
* @returns {String}
* @example AAMMAA -> Is a mirror string
* @example PAAAP -> Not a mirror string
*/

// time complexity of this algorithm is BigO(N/2) where N is length of string
const checkMirrorString = (inputString) => {
if (typeof inputString !== 'string') {
return 'Not a string'
}
if (!/^[a-zA-Z]+$/.test(inputString)) {
return 'String should only contains alphabet'
}
if (inputString.length === 0) {
return 'Input string should not be empty'
}
const lowerCaseSymmetricCharacters = new Set(['o', 'i', 'l', 'w', 'v', 'x'])
const upperCaseSymmetricCharacters = new Set([
'A',
'H',
'I',
'M',
'O',
'T',
'U',
'V',
'W',
'X'
])
let i = 0
let j = inputString.length - 1
let leftPointerCharacter
let rightPointerCharacter
while (i <= j) {
leftPointerCharacter = inputString.at(i)
rightPointerCharacter = inputString.at(j)
if (
(leftPointerCharacter === rightPointerCharacter &&
lowerCaseSymmetricCharacters.has(leftPointerCharacter)) ||
upperCaseSymmetricCharacters.has(rightPointerCharacter)
) {
i++
j--
} else {
return 'Not a mirror string'
}
}
return 'Is a mirror string'
}
export { checkMirrorString }
27 changes: 27 additions & 0 deletions String/test/CheckMirrorString.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { checkMirrorString } from '../CheckMirrorString'

describe('checkMirrorString', () => {
it('CheckMirrorString -> ', () => {
const word = 'HOAMMAOH'
const res = checkMirrorString(word)
expect(res).toBe('Is a mirror string')
})

it('check for npn mirror string -> ', () => {
const word = 'JAVASCRIPT'
const res = checkMirrorString(word)
expect(res).toBe('Not a mirror string')
})

it('string with numeric value -> ', () => {
const word = 'Kop12Po'
const res = checkMirrorString(word)
expect(res).toBe('String should only contains alphabet')
})

it('number as a string -> ', () => {
const word = 1234
const res = checkMirrorString(word)
expect(res).toBe('Not a string')
})
})