[算法编程]Longest String Prefix

本文基于学习
最近我在换工作,复习一些基础知识,并在面试过程中把遗忘的知识都捡起来。真的是,不经常用的东西都不会记住,忘得好快。囧。

javascript算法编程思考.jpg

昨天做了两个算法题,这是其中一个。
后来发现,原来这些题主要来自网站https://leetcode.com/,以前我也浏览过,不过基本都很好少看。

题目如下:

Longest String Prefix

Write a function that takes in a string and returns the length of the longeststring prefix in which all characters are arranged in alphabetical order
Note: The string contains onlu lower case letters from a - z

Example 1:
Input: "knotty"
Output: 6
Explanation: The longest prefix which follows alphabetical order is k, n, o, t, t, y.

Example 2:
Input: "apple"
Output: 3
Explanation: The longest prefix which follows alphabetical order is a, p, p.

Example 3:
Input: "excel"
Output: 2
Explanation: The longest prefix which follows alphabetical order is e, x.
Note that c, e, l is not a prefix because it does not start in the beginning of string.


# 常规思路
var longestStringPrefix= function(str) {
    if(str==null) {
        return;
    }
    var array = str.split("");
    var output = [];
    var length = array.length;
    for(var i =0; i<length; i++) {
        if(i==0) {
            output.push(array[i]);
            continue;
        }
        if(array[i]>=array[i-1]) {
            output.push(array[i]);
        } else {
            break;
        }
    }
    console.log(output);
    console.log(output.length);
}
longestStringPrefix("knotty");
longestStringPrefix("apple");
longestStringPrefix("excel");
# 输出
(6) ["k", "n", "o", "t", "t", "y"]
6
 (3) ["a", "p", "p"]
3
 (2) ["e", "x"]
2
# 优化:这样也行咯
var longStr = function(str){
    const arr = [];
    let s = [...str][0];
    [...str].forEach((i) => {
        if(s<i || s==i){
             s = i;
           arr.push(i);
        }
    });
    return arr;
}

longStr("knotty");
longStr("apple");
longStr("excel");

学习是一条漫漫长路,每天不求一大步,进步一点点就是好的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。