左旋转字符串
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
输入: s = "abcdefg", k = 2
输出: "cdefgab"
/**
* @param {string} s
* @param {number} n
* @return {string}
*/
var reverseLeftWords = function(s, n) {
return s.slice(n) + s.slice(0, n)
};
翻转单词顺序
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。
输入: "the sky is blue"
输出: "blue is sky the"
/**
* @param {string} s
* @return {string}
*/
var reverseWords = function(s) {
return s.split(" ").filter(item => !!item).reverse().join(" ")
};
把字符串转换成整数
写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。
/**
* @param {string} str
* @return {number}
*/
var strToInt = function(str) {
str = str.trim();
let res = parseInt(str);
if(isNaN(res)) return 0;
let minValue = Math.pow(-2, 31);
let maxValue = Math.pow(2, 31) -1
if(res < minValue) return minValue
if(res > maxValue) return maxValue;
return res
};
字符串轮转
字符串轮转。给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottle是erbottlewat旋转后的字符串)。
输入:s1 = "waterbottle", s2 = "erbottlewat"
输出:True
/**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var isFlipedString = function(s1, s2) {
if (s1 === s2) return true
let arr = s1.split('')
for (let i = 0; i < arr.length; i++) {
if (s1.slice(i) + s1.slice(0, i) === s2) {
return true
}
}
return false
};
字符串压缩
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
输入:"aabcccccaaa"
输出:"a2b1c5a3"
/**
* @param {string} S
* @return {string}
*/
var compressString = function(S) {
let res = ''
let i = 0
let j = 0
while(j < S.length) {
if (S[j] !== S[j+1]) {
res += S[j]+(j+1-i)
i = j+1
}
j++
}
return res.length < S.length ? res : S
};
回文排列
给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。
回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。
回文串不一定是字典当中的单词。
输入:"tactcoa"
输出:true(排列有"tacocat"、"atcocta",等等)
/**
* @param {string} s
* @return {boolean}
*/
var canPermutePalindrome = function(s) {
let arr = s.split('')
let map = new Map()
arr.forEach(item => {
if (map.has(item)) {
map.set(item, map.get(item)+1)
} else {
map.set(item, 1)
}
})
let count = 0
map.forEach(item => {
if (item % 2 === 1) {
count += 1
}
})
return count <= 1
};
URL化
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
/**
* @param {string} S
* @param {number} length
* @return {string}
*/
var replaceSpaces = function(S, length) {
let len = S.length
if (length > len) {
let arr = new Array(length-len).map(item => '')
S = S+arr.join('')
} else {
S = S.substr(0, length)
}
S = S.replace(/\s/g, '%20')
return S
};