按字母顺序排列的最长子字符串Javascript

时间:2015-06-21 16:52:05

标签: javascript

看到所有人在Python中按字母顺序谈论最长的子串,我决定在JS中尝试它。 该函数应查找给定字符串中最长的子字符串,其中字母按字母顺序排序。

这就是我所拥有的:

var s = 'azcbobobegghakl'

function substringChecker(s) {
	var longestSub = "";
	for (var i = 0; i < s.length; i++) {
		var count = 0;
		var currSub = "";
		while((i+count)<=s.length){
			var curr = i+count;
			var next = curr+1;
			var prev = curr-1;
			if(curr !== s.length-1) {
				if(s[curr] <= s[next]){
					currSub += s[curr]
				} else {
					break;
				}
			} else {
				if(s[curr]>s[prev]) {
					currSub += s[curr];
				}
			}
		count++;
		}
		if(currSub.length >= longestSub.length) {
			longestSub = currSub;
		}
	};
	return longestSub;
}
var result = substringChecker(s);;
console.log(result);

有趣的是它适用于我能想到的所有测试用例,但是这个。结果应该是“beggh”,但它是“begg”。为什么h没有出现,我缺少什么?

2 个答案:

答案 0 :(得分:1)

算法可以是线性的,我认为你过于复杂,它将循环放在循环中。

我会使用像

这样的东西

function substringChecker(s) {
  var longestSub = "",
      length = 0,
      start = 0,
      prev = s[0];
  for (var i = 1; i <= s.length; ++i) {
    if(i == s.length || s[i] < prev) {
      if(length < i-start) {
        longestSub = s.substring(start, i);
        length = i-start;
      }
      start = i;
    }
    prev = s[i];
  };
  return longestSub;
}
document.write(substringChecker('azcbobobegghakl'));

答案 1 :(得分:0)

首先我列出了A-z 然后检查每个字母并将其与下一个字母进行比较,并将其保存在subString中并...

function longest(str) {
  //handle the case str is just one letter
  if (str.length === 1) return str;
   // create a list of alphabet A to Z
  const alphabets = [...Array(26)].map(_ => String.fromCharCode(i++), (i = 97));
  let longString = "";
  let subSting = "";
  for (let x = 0; x < str.length; x++) {
    let char = str.charAt(x);
    const nextChar = str.charAt(x + 1);
    let charIndex = alphabets.findIndex(alphabet => alphabet === char);
    let nextCharIndex = alphabets.findIndex(alphabet => alphabet === nextChar);
    if (nextCharIndex >= charIndex) {
      subSting = subSting + nextChar;
    } else {
      if (!subSting.length) {
        subSting = subSting + char;
      }
      longString = subSting.length > longString.length ? subSting : longString;
      subSting = "";
    }
  }
  return longString;
}
console.log(longest("zyba"));