leetcode

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

commit e0e6250b3e369c90cbf8b61e2abfdfaf122a4ad0
parent 4f06a42e1feab07eccf60a29b0f768121fa01804
Author: AndrewLockVI <andrewlaack1@gmail.com>
Date:   Sat, 15 Apr 2023 20:05:42 -0500

Longest common prefixe problem complete

Diffstat:
Alongest-common-prefix/a.out | 0
Alongest-common-prefix/longest-common-prefix.cpp | 34++++++++++++++++++++++++++++++++++
2 files changed, 34 insertions(+), 0 deletions(-)

diff --git a/longest-common-prefix/a.out b/longest-common-prefix/a.out Binary files differ. diff --git a/longest-common-prefix/longest-common-prefix.cpp b/longest-common-prefix/longest-common-prefix.cpp @@ -0,0 +1,34 @@ +#include <iostream> +#include <vector> +using namespace std; + +//Runtime: 3ms Beats: 87.33% +//Memory: 9.3MB Beats: 54.69% + +string longestCommonPrefix(vector<string>& strs) { + int shortest = strs[0].size(); + for(int i = 1 ; i < strs.size() ; ++i){ + if(strs[i].size() < shortest){ + shortest = strs[i].size(); + } + } + char current; + string output = ""; + for(int i = 0 ; i < shortest ; ++i){ + current = strs[0][i]; + for(int x = 0 ; x < strs.size() ; ++x){ + if(strs[x][i] != current){ + return output; + } + } + output += current; + } + return output; +} + + + +int main(){ + vector<string> strings = {"Cat","Cap", "Cab"}; + cout << longestCommonPrefix(strings) << endl; +}